Some tips for using Laravel

Tram Ho

1. updateOrCreate.

  • If you need to check if the record exists, then update it or create a new one, you can do it in an updateOrCreate () statement.

2. Eloquent relationships

  • You can specify orderBy () directly on your Eloquent relationships.

3. Eloquent method latest / oldest.

  • Instead of using order by created_at desc / asc, you can use the Eloquent method latest / oldest.

4. Query Scopes

  • You can combine query and query scopes in Eloquent, using multiple scopes in a single query.

5. Auth

  • If you want to get ID of the logged in user.

6. Foreach loop

  • In Blade, inside the @foreach loop, with the $ loop variable, you can check if the current element is its first, last, or number in the iteration.

  • To foreach the elements of the array and print out the STTs of the items.

  • Instead of writing {{ $index + 1 }} , you can use the variable $ loop as follows {{ $loop->iteration }}
  • The $ loop variable also contains many other useful properties. Read more

7. Accessors & Mutators

  • Accessors : Define the method to get the desired data based on the properties of the model eg:
  • To display the full name, you must add the string as follows.

  • You can define a method to handle this.

  • To get the full name, just call

  • Mutators : Will set the value of the model before saving it to the database

8. Where attribute

  • Normally, when using where, we would write the following:

  • But can write more concisely.

  • You can where any field similar to the one above e.g. role_id -> whereRoleId, status -> whereStatus

9. Soft-deletes

  • Be careful with the soft delete and query builder operations. Don’t forget that soft delete will exclude items when you use Eloquent, but won’t work if you use the query builder.


  • To make your code more readable to others, instead of using hard-coded numbers for some values, set them to connst constants with explicit names.

Share the news now

Source : Viblo