In our regular development life we are trying to do more better and efficient code. But the thing is that many developers don’t know the proper shortcuts & efficient helpers and many more things which helps to make more better coding. I listed here some shortcut of syntax which are helpful for you.
Common Syntax Vs Shorter Syntax
Some of Laravel Eloquent hidden gems
- Conditional DB Query
Sometimes we need conditional query but when the both result (or none ) returns true, then we generally do separate eloquent calls as like
Another better way to repeat eloquent call
- Use where() on a with() by using whereHas()
If you want to need of constraints on models’s relationship then return those result whose relationship match that constraint, hahahahah… It’s much better solution
->whereHas() checks that
- The relationship exists
- Allows you to pass a closure that you can use to add constraints to the query being called
- Using the shorter where method for date column
The below method is most important, it’s a recommendation to use those filter for date column intend of where clauses or looping through the returned collection to breakdown the date and grab only ones from a particular month.
- Only return models if they have a particular relationship using has().
The below example says required ->has(‘specification’) means return those eloquent model whose records exist in DB.
- Use of (skip / take) instead of offset and limit
To limit the number of results returned from the query or to skip a given number of results in the query. It is easy to read & sort as like skip(10) users and take(5)