We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
There are a few traits built into Laravel that can become very useful in your own classes. One example is the
Illuminate\Support\Traits\Conditionable
trait. This trait allows you to easily add conditional clauses to your queries.
An example use-case is the Laravel Eloquent query builder
when
method. This method
allows you to add a conditional clause:
<?php
$isAdmin = $request->input('is_admin');
$books = Book::query()
->when($isAdmin, function ($query, $role) {
return $query->where('is_draft', 1);
})
->get();
In this example, only admins will get to see the books that are published.
There's also the opposite call unless
:
<?php
$isAdmin = $request->input('is_admin');
$books = Book::query()
->unless($isAdmin, function ($query, $role) {
return $query->where('is_draft', 0);
})
->get();
You can easily add the functionality to your own classes by simply adding the
Illuminate\Support\Traits\Conditionable
trait:
<?php
use Illuminate\Support\Traits\Conditionable;
class Action
{
use Conditionable;
public function actionA(): void {
}
public function actionB(): void {
}
}
It can then be used as:
<?php
$action = new Action();
$action->when($condition, function (Action $action) {
$action->doSomething();
});
$action->unless($condition, function (Action $action) {
$action->doSomethingElse();
});
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.