Using Virtual Columns in Laravel - Accessors and Appends

What are virtual columns? 
While developing any web application sometimes we need virtual columns - columns don't actually exist in our DB table, but we drive them from other columns.
Why we need them?
For example, generally, we use first_name and last_name in the users table. But sometimes we also need user's complete name i.e. full_name. There is no benefit of saving full_name in user table if we have already first_name and last_name in the table OR even if we have full_name as a column in our table then there is no benefit of saving first_name and last_name in the table. So in a scenario like this, we prefer to use the virtual column.

Using Virtual Columns in Laravel
Considering the first case, in Laravel to get virtual column i.e. full_name from the users table will have Accessors.
Accessors are methods defined automatically called by Eloquent when select is called on that particular column.

Let take an example here:
To get full_name in above case write below method in user model i.e. app\User.php
public function getFullNameAttribute()
{
    return $this->first_name . " " . $this->last_name;
}
Accessor method name for any column starts with 'get' followed by column-name in PascalCase ends with 'Attribute'. i.e. get{FullName}Attribute.

Above method will above you to get full_name over the object of user record i.e.
  User::find(1)->full_name;
That will fulfill your need in many cases.

Not what if in some case you need custom select query only to pick selected columns OR you return Array or JSON instead User Object. You will go like :
User::select('first_name', 'last_name', 'email',
DB::raw("concat(users.name, ' ', users.last_name) AS myname"))
->where('id', 1)
->get()
->toArray();

So here $appends will help you.

$appends is property offered by Eloquent which appends the given array of attributes to collection-data. After adding the virtual column name in $appends it will be accessible in both the model's array and JSON representations not only record Object.

You can define $appends in your model class as below:
class User extends Model
{

//
$appends = [
    'full_name'
];
So our model class will look like:
class User extends Model
{

//
$appends = [
    'full_name'
];

public function getFullNameAttribute()
{
    return $this->first_name . " " . $this->last_name;
}
Now above select query can be written as:
User::select('first_name', 'last_name', 'email')
->where('id', 1)
->get()
->toArray();
Here we have not mentioned full_name column in the select query but it will automatically append to collection-data by Eloquent. 

Comments

Popular posts from this blog

How to Show Cookie Policy Consent or GDPR Popup in Laravel using Cookie.

Postman Collection Run - How to Test File Uploading API on CircleCi or Jenkins