Laravel Eloquent — 5 Tips & Tricks

Eloquent may be Laravel’s most powerful feature, and it has so much depth I thought I should write a short list of my favorite tips and tricks I’m using every day.
1. When
The when() “Apply the callback if the given “value” is (or resolves to) truthy” (super simple, super useful, avoid ‘ifs’, be better).
User::query()
->when($request->filled('user_type_id', fn($query) => $query
->where('user_type_id', $request->input('user_type_id'))
)
->get();Apply the callback if the given “value” is (or resolves to) truthy.
2. WithWhereHas
Apply a relationship condition while eager loading it. WithWhereHas can also take an optional callback method as second parameter:
$authors = User()
->withWhereHas('articles', fn($query) => $query
->whereNot('status', Article::STATUS_ARCHIVED)
)
->get();Add a relationship count / exists condition to the query with where clauses. Also load the relationship with same condition.
3. With
Everyone — should — know about the with method, that eager-loads relations into your models (n+1 is evil).
- You can add specific columns to select by adding :column1,column2 after your relation’s name.
- You can use both array and dot notation.
$authors = User::query()
->with([
'profile:id,user_id,first_name,last_name',
'articles' => [
'draft:id,article_id',
'cover:id,disk,path,name',
],
])
->get();Begin querying a model with eager loading.
4. FindOr
Quick, simple & pwetty 🦋. The best way to impress your colleagues with obscure methods no-one uses.
$authors = User::query()
->findOr($request->input('author_id'), static function () {
return Redirect::back()->withErrors('Given author id does not exist');
});Find a model by its primary key or call a callback.
5. DB Commit/Rollback
Allow you to rollback unwanted database transactions.
- DB::beginTransaction(): Start a new database transaction.
- DB::rollback(): Rollback the active database transaction.
- DB::commit(): Commit the active database transaction.
\DB::beginTransaction();
// Building and running requests...
if (! $fooIsValid) {
// 🚫 Oops, something went wrong, rollback requests.
\DB::rollback();
}
// Request is now committed ✅
\DB::commit();Hope you enjoyed!