Storing different types of data in a database often involves a variety of tricks. For example, in order to save an array to the database in PHP, you first need to serialize it, and upon receipt, execute unserialize. To simplify this and other similar tasks, there is already a special tool: type casting in Laravel, which we will talk about today. It is often used when developing large projects, for example, when creating a shop in Laravel 8.

How to store different types in Laravel?

To begin with, I suggest looking at what conversions you probably did before saving the array to the database, if you are not already familiar with type casting.

Wrong way:

// save data with Eloquent
$user->settings = serialize($settingsArray);

In the database, the settings column is of type text, into which a serialized array is passed (in one line). In this case, when get data in the application, you will have to do the opposite.

// get data with Eloquent
$user = User::where('id', $id)->first();
$settingsArray = unserialize($user->settings);

As you can see, you have to do additional completely optional data manipulations, but with the help of Type casting in Laravel, they can be completely avoided.

Good way:

In order for Laravel to transform the data for you, it is enough to add the $casts property to the model in which you are working. For example, for the example given earlier, you will need to do this:

class User extends Authenticatable
protected $casts = [
    'settings' => 'array'

Now, when saving data, type casting will do everything for you and you can assign an array to the model property and Eloquent will figure out how to save it.

// save data with Eloquent
$user->settings = $settingsArray;

And when received, Laravel will also transform it itself.

Convenient, isn’t it?

The $casts property must contain the name of the model attribute as the key and the data type as the value.

Type casting in Laravel is possible for: array, boolean, integer, date, collection and other types (the full list can be found in the official documentation).

The use of type casting greatly simplifies the work with the database and reduces the amount of repetitive logic in the code. It is also very convenient, for example, when working with a date in Laravel.

If the article turned out to be useful to you, do not forget to subscribe to Twitter and be the first to know when new articles are released.

Share post
Twitter Facebook