Accessors and Murators in Laravel 7.x

Tram Ho


Accessors and Murators allow you to format Eloquent properties when we retrieve or add new models. For example, when adding a user you want before adding, it automatically encrypts the value of the password before being saved to the database or retrieving a name from the database as a print. flowers then accessors and murators will help us to do this. In addition, Eloquent can also automatically convert the date field into a Carbon instance or convert a text into a json data type.

1. Define an Accessors

In a nutshell, accessors will help us format the data when we get data from the database. Suppose we have the name field in the user table and want to retrieve the data it will be in uppercase. First we need to create a method to define this in the User model as get + tên trường in hoa chữ cái đầu + Attribute . In this case, the method written will be getNameAttribute .

Now try to see how the result is, you will create a route as follows:

Now go to localhost: 8000 / accessors and see the results.

Or you can even define a new property with existing attributes, for example:

The procedure is similar

2. Defining a murators.

Unlike accessors , murators used to format data before saving it in a database. To define a murators closely resembles accessors only difference is that the prefix will be set . For example, we will format the name field to be not capitalized before being saved into the database. So the method here will be setNameAttribute

To test we also create a route with the following content:

To check if the data is saved properly or not, open the php artisan tinker to check AppUser::find(1) , we will see that the value of the newly saved name field will be ccc .

3. Date Murators

By default, Eloquent will automatically convert the created_at and update_at fields to the Carbon instance, and it provides a lot of useful functions. We can also add date properties by using $date in the model

When a field is of type date you can set its value to a UNIX timestamp , date string (Ymd), date-time string or an instance of Carbon, and the value of the date will automatically be stored in the database.

Date formats

By default the timestamps are formatted as Ymd H:i:s , you can dateFormat this format by using the dateFormat property in the model, this property will reformat as the date data type to be saved. in the database.

4. Attribute Casting

The $cast attribute helps convert attributes to normal data types. The $cast attribute is usually an array where the key is the name of the property to be transferred and value is the type of data you want to transfer. The data types that the $cast attribute supports: integer, real, float, double, decimal:<digits>, string, boolean, object, array, collection, date, datetime, and timestamp . For example, we have the is_admin property stored in the database as 0 and 1 with integer data types but you want to use it as a boolean data type, do the following

Then we use is_admin as a property of boolean data type

Custom cast

You can define your own cast attribute by creating an implements class from the CastsAttributes interface. One thing to note is that this newly created class must have two get and set methods with different tasks. The get method is used to convert data in the database to the cast data type that you define, while the set method has the opposite task to convert the converted data into the original data type to store in the database. For example, we custom cast attribute is json data type.

Then we will use it in the model.

Array & JSON Casting

Cast array Cast very useful when we use them with a column saved as json.

When declared like this, we will use and process the data as an array in PHP. When you set the value for the options attribute, the given array will automatically be converted back into JSON to store:

Date Casting

When using cast with a date and datetime data type, we can reformat it

Query Time Casting

Sometimes you can even use cast in your queries

The last_posted_at attribute is based on the result of the selectRaw statement, it would be more reasonable if we set the data type for last_posted_at be of a date type, simply by using the withCasts method.

You can also see how other usefulness the cast attribute brings here .

Share the news now

Source : Viblo