Laravel Type Casting

Mohd Suhail
2 min readJul 2, 2023

Type casting in Laravel allows you to specify the data types for individual attributes in a model. Laravel automatically converts attribute values to the relevant types when you fetch data from the database depending on your casting definitions.

You Can Find Various Attribute Types Here Casting

Here are the different types of type casting available in Laravel:

  1. Integer::It changes the attribute into an integer.
  2. Real::It converts the attribute into an actual number.
  3. Float:: This attribute is converted to a floating-point number.
  4. Double:: This attribute is converted to a double-precision floating-point number.
  5. String:: This function converts the attribute to a string.
  6. Boolean::It transforms the attribute into a boolean value.
  7. Object::It transforms the attribute into a PHP object.
  8. Array: :This function converts the attribute to a PHP array.
  9. Collection::It transforms the attribute into a Laravel collection.
  10. Date:: This attribute is converted into a date format (Y-m-d).
  11. DateTime:: This attribute is converted into a DateTime instance.
  12. Timestamp:: This attribute is converted into a Unix timestamp (integer).
<?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',
'age' => 'integer',
'data' => 'array',
'created_at' => 'datetime',
];
}
  • age is casted to an integer. Similarly, when fetching the age attribute, it will be automatically casted to an integer.
  • data is casted to an array. This attribute will be interpreted as an array when retrieving it from the database.
  • created_at is casted to a datetime. This means that the created_at attribute will be treated as a DateTime object when accessed.
  • is_admin is converted to a boolean value. This indicates that when we fetch this attribute from the database, it will behave as a boolean value (true or false).

As a result, you can store JSON tags data in a user database, but when you get the users, you can simply transform them into a PHP array, eliminating the need to set up a tags table.

When working with attributes in your Laravel models, type casting simplifies the handling of data types without the need for manual conversions each time you access or modify an attribute’s value. Laravel’s type casting feature automates this process, enhancing code readability and maintainability.

Thanks Every One

--

--

Mohd Suhail

I'm a Full-stack developer with a passion for software architecture and programming best practices. I love writing clean code, talking and writing about it .