This article is forwarded to the professional Laravel developer community, original link: learnku.com/laravel/t/3…

When I first started developing at Laravel, I felt there were a lot of things that could have been done better in implementing the model. After exploring the Eloquent Model class, I found that you can do some fun things with your model that will make you feel even more relaxed.

In this article, I’ll give you seven tips that everyone who uses Laravel knows how to make the most of your model.

#1 First, let’s start by creating the model

When we create a model from the command line, you can specify a folder in which to create the model. All you have to do is type the name of your folder before the model name. This is helpful when your model is not stored in the default app folder.

php artisan make:model Models/Product
Copy the code

At this point, a Product model will be created in the App /Models folder, which will save you time to move the model to the appropriate folder.

#2 Convert the property type

The $casts property provides methods to cast the property to some data type.

protected $casts = [
    'is_published'= >'boolean'
];
Copy the code

The IS_Publish property will now cast to Boolean when you access it, even if it stores an INTEGER in your database. There are also many ways to convert properties to other types, such as Date and Datetime.

A common error I see is to format date and datetime in a Blade template file, like this:

{{ $blog->created_at->format('Y-m-d')}}Copy the code

In some Blade template files, you will see multiple formatting on the same variable. This problem can be solved more efficiently with the $casts attribute.

For date and datetime conversion attributes, you can specify the following format:

protected $casts = [
    'published_at'= >'datetime:Y-m-d',];Copy the code

This will always return the published_AT attribute in y-m-D format, so you no longer need to do any formatting in the Blade template file.

#3 is visible

Some properties, such as password properties, should not be included in an array or JSON representation of the model. This is where the $hidden property comes in.

protected $hidden = [
    'password'
];
Copy the code

visibleProperty to set the whitelist of properties.

protected $visible = [
    'first_name'.'last_name'
];
Copy the code

When set in the modelfillable 和 $guardedSame property.

# 4 accessors

Sometimes you want to combine multiple attributes into one, or you just want to format the attributes. At this point we can use Laravel’s accessor.

Suppose you have a User model and they have first_name and last_name attributes. If you want to display the full name, you can do this:

$this->first_name . ' ' . $this->last_name
Copy the code

This is a very naive approach. The solution to this problem in Laravel is to use accessors. The accessor defines a method in the model using the following syntax:

get[NameOfAttribute]Attribute
Copy the code

An access to get the full name would look like this:

public function getFullNameAttribute() {
    return "{$this->first_name} {$this->last_name}";
}
Copy the code

To get the full value, you simply call the accessor like this:

$user->full_name
Copy the code

# 5 modifier

Modifiers allow you to manipulate values and set action values on the * $Attributes * property of the model. Variables have the same syntax as accessors.

public function setLastNameAttribute($value) {
    $this->attributes['last_name'] = ucfirst($value);
}
Copy the code

The mutator will apply the * ucFirst * function to the last name and store the result in the * $attributes * attribute.

$user->last_name = 'jones'; // The result will be 'Jones'Copy the code

# 6 additional value

When a model has accessors and model associations, they are not added to the array or JSON representation of the model by default. To do this, you need to add an accessor or model association to the $Appends property of the model. Now let’s continue with the example of the getFullNameAttribute accessor:

$appends = [
    'full_name'
];
Copy the code

Note: Accessors added to the $Appends property are referenced in the snake nomenclature, even if accessors are defined in camel nomenclature.

Let’s assume that the User model has a one-to-many relationship with the Blog model.

public function blogs() {
    return $this->hasMany(App\Blog::class);
}
Copy the code

To add blogs to the model, you simply add them to the $Appends property:

$appends = [
    'full_name'.'blogs'
];
Copy the code

Of course, we can specify the attributes to add. For example, if you only need the ID and title from the blog to be added to the model.

$appends = [
    'full_name'.'blogs:id,title'
];
Copy the code

#7 Finishing touches

When a model has a BelongsTo or BelongsToMany relationship with another model, such as Comment belonging to a Blog, it can be helpful in some cases to update the parent timestamp when updating the child data. This can be done by adding the relationship to the $Touches property.

class Comment extends Model
{
    protected $touches = ['blog'];

    public function blog()
    {
        return $this->belongsTo(App\Blog::class); }}Copy the code

When the Comment model is updated, the updated_AT property of the Blog model is also updated.