What is casting ?
Casting a value means changing the data type of a value to another one or a particular type. Like PHP , every programming languages has it’s own primitive types and you might already heard ‘integer’ or ‘double’ or ‘boolean’. The most common ones actually.
Attribute casting is a feature of Eloquent ORM which allows you to set your model to automatically cast a particular attribute to a certain type.
In short, you stored your data to a specific format to the database but you want to display the data in a different format after retrieving. casting sits in between them.
Why I need casting ?
A basic scenario as an example for this feature is , you stored number to database and when the returned , they returned as string by default. But the eloquent attribute casting allows you to return that as string, double, float or even boolean(in case your stored data is 0 or 1, you can return them as true or false.)
Enough talk. Show me practical example
To cast an attribute, you need to explicitly call an array named $casts in your eloquent model, like the following:
class User extends Model
* The attributes that should be casted to native types.
* @var array
protected $casts = [
'age' => 'integer'
dd($user->age); // wil print int(value)
For more you can check the documentation Here