How To Use Attribute Casting In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

In Laravel Attribute casting means, changing the value of an attribute to a particular data type like boolean, integer, strings or array. To cast an attribute value of a Laravel Eloquent model, all you have to do is add them to the $casts property of the model class with their desired type.so today we are going to discuss how to use Attribute casting in laravel

How To Use Attribute Casting In Laravel With Example

Attribute Casting

The $casts property on your model provides a convenient method of converting attributes to common data types.

The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to.

The supported cast types are: 

  • integer
  •  real
  •  float
  • double
  •  decimal:<digits>
  • string
  • boolean
  • object
  • array
  • collection
  • date
  • datetime
  • timestamp.

When casting to decimal, you must define the number of digits (decimal:2).

To demonstrate attribute casting, let's cast the email_verified_at attribute, which is stored in our database as an integer (0 or 1) to a boolean value:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}


Now the email_verified_at attribute will always be cast to a datetime when you access it.

So, for example

Create Route in Web.php file as below

Route::get('/cast ', 'demoController@cast')->name('cast');


Create demoController and implement code to get the name 

php artisan make:controller demoController -mcr
 

Open demoController.php in app\Http\Controller folder and implement code as below

public function cast()
{
    $user = User::find(1);
    return $user->email_verified_at;
}


Attributes that are null will not be cast. In addition, you should never define a cast (or an attribute) that has the same name as a relationship.

Related Post