7 things you need to know to get the most out of your Laravel Model

7 things you need to know to get the most out of your Laravel ModelDaanBlockedUnblockFollowFollowingApr 27When I first started developing in Laravel I felt like there were a lot of things that could be done in a better way when it comes to implementing models.

After diving in the Eloquent Model class, I found some interesting things that you can do with your models to make your life a lot easier.

In this article I will give you seven tips that everyone using Laravel should know to get the most out of your models.

#1 First things first, let’s start by creating a modelWhen creating a model via the command line, you can specify the folder in which the model should be created.

All you have to do is type the name of the folder in front of the model name.

This is helpful when your models are not stored in the default app folder.

php artisan make:model Models/ProductThis will create a Product model in the app/Models folder, which saves you time moving your model manually to the correct folder.

#2 Casting attributesThe $casts property provides a way to cast attributes to certain data types.

protected $casts = [ 'is_published' => 'boolean'];The is_publish attribute will now always be cast to a boolean when you access it, even when it is stored as an integer in your database.

There are a lot of types where you can cast your attributes to, like date and datetime.

A mistake that I often see is that date and datetime attributes get formatted in Blade templates, like this:{{ $blog->created_at->format('Y-m-d') }}In some Blade templates you will see that formatting happens multiple times on the same variable.

This could be done more efficiently via the $casts property.

For date and datetime casts you can specify the format:protected $casts = [ 'published_at' => 'datetime:Y-m-d',];This will always return the published_at attribute in the Y-m-d format, so you don’t have to do any formatting in the Blade templates.

#3 VisibilitySome attributes should not be included in the array and JSON representation of a model, for example a password attribute.

This is when the $hidden property comes in to play.

protected $hidden = [ 'password'];The $hidden property acts like a blacklist for attributes.

Alternatively you can use the $visible property to whitelist attributes.

protected $visible = [ 'first_name', 'last_name'];When the $visible property is set on the model the rest of the attributes will automatically be hidden.

This works just like the $fillable and $guarded properties.

#4 AccessorsSometimes you want to combine multiple attributes into one or you just want to format an attribute.

This can be done with accessors in Laravel.

Suppose that you have an User model which has a first_name and last_name.

If you want to display the full name you could do it like this:$this->first_name .

' ' .

$this->last_nameThis is a very naive approach.

The Laravel way to solve this problem is with an accessor.

An accessor is a method that is defined in a model with the following syntax:get[NameOfAttribute]AttributeThe accessor for the full name would look like this:public function getFullNameAttribute() { return "{$this->first_name} {$this->last_name}";}To access the full name value of the accessor you would have to call it like this:$user->full_name#5 MutatorsMutators allow you to manipulate the value and set the manipulated value on the $attributes property of an Eloquent model.

Mutators have the same syntax as accessors.

public function setLastNameAttribute($value) { $this->attributes['last_name'] = ucfirst($value);}This mutator will apply the ucfirst function to the last name and store the result in the $attributes property.

$user->last_name = 'jones'; // Will result in `Jones`#6 Appending valuesWhen a model has accessors and relations they are not added to the array and JSON representation of the model by default.

To do this you have to add the accessor or relation to the $appends attribute of the model.

Let’s stick with the example of the getFullNameAttribute accessor for now:$appends = [ 'full_name'];Note:Accessors added to the $appends attribute are referenced in snake case even though the accessor is defined in camel case.

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

public function blogs() { return $this->hasMany(AppBlog::class);}To append the blogs to the model you can simply add them to the $appends attribute:$appends = [ 'full_name', 'blogs'];It is also possible specify the attributes that should be appended.

For example, if you only want the blog id and title to be appended to the model.

$appends = [ 'full_name', 'blogs:id,title'];#7 TouchesWhen a model has a BelongsTo or BelongsToMany relationship with another model, in this case a Comment that belongs to a Blog, it could in some cases be helpful to update the parent’s timestamp when the child is updated.

This can be done by adding the relationship to the $touches attribute.

class Comment extends Model{ protected $touches = ['blog']; public function blog() { return $this->belongsTo(AppBlog::class); }}When the Comment model get’s updated this will automatically update the updated_at attribute of the blog aswell.

This are the seven things that I wanted to share with you to get the most out of your models.

If these tips helped you in any way make sure to check out my other posts aswell.

Please feel free to leave a comment if you have any feedback, questions or want me to write about another Laravel related topic.

.

. More details

Leave a Reply