Tips in Laravel you may not know. (Part 2)

Tram Ho

Laravel is one of the most popular PHP Frameworks today, with great support for most developer requirements. However, besides the features written in documents, Laravel has many hidden features. In this article, I will share the tips about Laravel that I have collected.

See also: Tips in Laravel you may not know. (Part 1)

1. Model all: columns

When using Model::all() , you can select the columns you want to retrieve from the database.

2. How to avoid errors in {{$ post-> user-> name}} if the user does not exist?

When defining a relationship, you can assign the default model with withDefault() to avoid errors when calling {{ $post->user->name }} if $post->user does not exist.

3. Conditions in a relationship

4. Write neat where in Query Builder

The 3 code snippets below are similar:

5. Update parent timestamps relationship

When a Model is related to belongsTo or belongsToMany another Model, for example, Comment belongsTo Post. If you want to update the parent Model’s timestamp when the child Model is updated, for example, when the Comment is updated, the updated_at field of Post will be updated as well. You only need to add the $touches to the Model.


When you perform an update comment like the one below, Post’s updated_at field will automatically update.

If you have the $touches but in some cases you don’t want to update the parent Model’s timestamp, you only need to add the options ['touch' => false] and the save() method.
Chia sẻ bài viết ngay

Nguồn bài viết : Viblo