In Laravel, we often need to add custom fields to our Eloquent models to make data handling easier. For example, in a user system, we might have two columns in the users table: name and lastname. If we need to display the user's full name instead of concatenating these two fields every time, we can simplify the process by creating a custom attribute in our model.
To do this, we're going to add a field called full_name in our User model, which will concatenate the name and lastname fields. This way, instead of manually concatenating in the view, we'll simply use the full_name attribute. This custom field will be created using an Accessor in Eloquent. Here's how to do it:
Open the User model file and add the following method:
public function getFullNameAttribute() { return $this->name . ' ' . $this->lastname; }
This getFullNameAttribute method creates the full_name attribute that concatenates the first and last name.
Once you have defined the Accessor, you can access the full_name attribute like this:
$user = User::first(); {{ $user->full_name }}
This will display the user's full name without having to manually concatenate in the view.
When using Eloquent to return data in an API, the full_name custom attribute will not be included in the JSON response by default. To ensure that your model includes this attribute in the response, you must add the attribute to the $appends array in your model:
protected $appends = ['full_name'];
With this setup, the model will automatically include the full_name attribute along with the other attributes in the JSON response:
return response()->json($user);
This way, the returned JSON collection will include the full_name attribute, making it easier to manipulate and display the data in your API.
Page loaded in 26.82 ms