Current Location: Home> Latest Articles> Complete Guide to Data Type Casting in Laravel 5.6

Complete Guide to Data Type Casting in Laravel 5.6

gitbox 2025-07-08

Introduction to Data Type Casting in Laravel

Laravel is a powerful PHP web framework that provides various tools such as Eloquent, Presenter, and Cast to improve development efficiency. Among these, the Cast feature stands out by allowing automatic conversion of database fields into specific PHP data types, making data handling simpler and cleaner.

Prerequisites

This guide uses Laravel 5.6 as an example. It assumes that you have a basic understanding of Laravel, including concepts like models, migrations, and Artisan commands.

Creating a Model and Table

Start by creating a model and its related resources using the Artisan command:

php artisan make:model Post -a

This command creates a Post model along with a migration file, a controller, and resource views.

Adding Casts to the Model

Laravel makes it easy to cast attributes to common data types using the $casts property on a model. To cast the published attribute to a boolean, add the following to your Post model:

protected $casts = [
    'published' => 'boolean',
];

With this setup, whenever you retrieve or assign a value to published, Laravel will automatically cast it to a boolean.

Testing the Casting Functionality

You can test this feature using Laravel's tinker tool:

$post = new Post;
$post->published = 1;
$post->toArray();

The output should show the published field as true, confirming that the casting is working properly.

Creating a Custom Cast

Laravel also allows you to define custom casting logic for special use cases. For example, if you receive a UNIX timestamp from an external API and want to convert it to a DateTime object:

use Carbon\Carbon;

protected $casts = [
    'published_at' => 'datetime',
];

public function setPublishedAtAttribute($value) {
    $this->attributes['published_at'] = Carbon::createFromTimestamp($value);
}

This example demonstrates how to convert a UNIX timestamp into a Laravel-compatible DateTime object using the Carbon library.

Conclusion

Laravel's Cast feature simplifies data type conversion by automatically transforming model attributes into the desired types. Whether you're working with booleans, integers, datetimes, or need custom logic, the $casts array provides a clean and consistent approach. By leveraging this feature, you can write less repetitive code and maintain cleaner, more reliable models.

Understanding and utilizing casting will help you handle data more efficiently and improve the quality of your Laravel applications.