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:
integerrealfloatdoubledecimal:<digits>stringbooleanobjectarraycollectiondatedatetimetimestamp. 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.