Laravel Eloquent Tips and Tricks Speedup your code #3
Eloquent ORM appears to be a simple method, but there are many semi-hidden functions and lesser-known ways to get more out of it. I’ll show you a few tips in this article.
- Avoid errors by using the optional helper
When accessing object values, if that object is null, your code will raise an error. For example:
return $invoice->total;
Would raise an error if the invoice object was empty. A simple way of avoiding errors is to use the optional Laravel helper:
return optional($invoice)->total;
Now, if the $invoice object is null, your code will return null instead of raising an error. You may also use a closure with the optional helper. It receives the closure as it’s second argument and it will be called if the first argument is not null.
2. Update or create
When working with databases, it’s customary to see if a given record already exists and update it, or to create a new record if it doesn’t. Something along these lines:
You can use Eloquent’s updateOrCreate method instead:
3. Looping variable in foreach
Inside of foreach loop, check if current entry is first/last by just using $loop variable.
There are also other properties like
More here: https://laravel.com/docs/master/blade#the-loop-variable
4. Route Group
Route group within a grouping Routes, you can create a group within a group, assigning a certain middleware only to some URLs in the “parent”
5. Eloquent where date methods
In Eloquent, simply to check the date with functions whereDay() , whereMonth() , whereYear() ,
whereDate() and whereTime() .
6. Testing email into laravel.log
If you want to test email contents in your app but unable or unwilling to set up something like Mailtrap, use .env parameter MAIL_DRIVER=log
and all the email will be saved into storage/logs/laravel.log file, instead of actually being sent.
7. Specific column Model on method ::all()
When calling Eloquent’s Model::all() , you can specify which columns to return.
$users = User::all([‘id’, ‘name’, ‘email’]);
8. Alias Column name in elequent
in Eloquent Query Builder, you can specify “as” to return any column with a different name, just
like in plain SQL query.
9. Use hasMany to create Many child
If you have hasMany() relationship, you can use saveMany() to save multiple “child” entries from your “parent” object, all in one sentence.
10. Method dd(Dump and Die)
One of the most common ways to debug an error in Laravel ecosystem is to dump the variable on the screen, and figure out what is going wrong with it.
The dd function dumps the given variables and ends execution of the script. Instead of doing dd($result); you can put ->dd() as a method directly at the end of your Eloquent sentence, or any Collection
Thanks for reading this article! Don’t forget to clap 👏 or leave a comment 💬