Casting Attribute in Laravel Eloquent Models

  • 29-05-2022
  • 1526
  • Laravel 9
  • Haresh Chauhan

The casting attribute in laravel provides similar functionality to use all that call without defining any additional methods. Instead $casts attribute provides in model common database in eloquent query model. Also, you can make it manually as you want to make it with your self logic.

$casts will use for common database attributes for the whole model in the laravel, There you don't need to define and additional method for it, Once define that attribute will apply in whole class's attribute as its matching attributes in casts key.

How To Use Casts?

The $casts property should always be in an array while the key is the name of the attribute being cast the value of the column will change in a different database.

Example 1:

Simple determine casts in the model.

protected $casts = [
    'email_verified_at' => 'datetime',
    'create_at' => 'datetime:Y-m-d H:i:s',
    'updated_at' => 'datetime:Y-m-d H:i:s',
    'status' => 'boolean',
    'password' => 'encrypted',
];

Above exmaple to determine the status attribute as boolean,create_at and updated_at attribute date format will datetime:Y-m-d H:i:s.

Example 2:

Simple exmaple casts use in model with protected.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */

    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

After defining is_admin attribute in cast, So the is_admin attribute will alwasy be cast as boolean, When you will access the is_admin attribute it will return boolean always.

$user = App\Models\User::find(1);
 
if ($user->is_admin) {
    //
}

But sometimes you don't wise to collection data with a cast, That time using mergeCasts for that query result the casts will not apply from the model for the temporary base.

$user->mergeCasts([
    'is_admin' => 'integer',
])

if ($user->is_admin == 1) {
        
}   

Example 3:

Also, you can use eloquent queries too:

$user = App\Models\User::query()
->where('id',1)
->withCasts([
    'is_admin' => 'boolean',
])
->first();

if($user->is_admin){
    // TRUE
}

Using able example you will just get only for that query result. Casts attribute will apply for that query only. while the protected $casts will apply in whole model.

Some Additional Casts Type

Here below is some supported default cast type list:

  • array
  • AsStringable::class
  • AsStringable::class
  • boolean
  • collection
  • date
  • datetime
  • immutable_date
  • immutable_datetime
  • decimal:
  • double
  • encrypted
  • encrypted:array
  • encrypted:collection
  • encrypted:object
  • float
  • integer
  • object
  • real
  • string
  • timestamp

Apart from that, you can also make yourself Custom Casts cast type.

Thanks for reading our post.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :