EN ES
Home > Web development > Laravel Tutorials > How to Add Custom Attributes to Eloquent Models in Laravel

How to Add Custom Attributes to Eloquent Models in Laravel

Diego Cortés
Diego Cortés
June 20, 2018
How to Add Custom Attributes to Eloquent Models in Laravel

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.

Creating a Custom Attribute

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:

Defining the Accessor in the Model

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.

Accessing the Custom Attribute

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.

Returning the Custom Attribute in JSON

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.

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 26.82 ms