#development #laravel #php

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:

1$isAdmin = $request->input('is_admin');
2
3$books = Book::query()
4    ->when($isAdmin, function ($query, $role) {
5        return $query->where('is_draft', 1);
6    })
7    ->get();

In this example, only admins will get to see the books that are published.

There's also the opposite call unless:

1$isAdmin = $request->input('is_admin');
2
3$books = Book::query()
4    ->unless($isAdmin, function ($query, $role) {
5        return $query->where('is_draft', 0);
6    })
7    ->get();

You can easily add the functionality to your own classes by simply adding the Illuminate\Support\Traits\Conditionable trait:

 1use Illuminate\Support\Traits\Conditionable;
 2
 3class Action
 4{
 5    use Conditionable;
 6
 7    public function actionA(): void {
 8    }
 9
10    public function actionB(): void {
11    }
12}

It can then be used as:

1$action = new Action();
2
3$action->when($condition, function (Action $action) {
4    $action->doSomething();
5});
6
7$action->unless($condition, function (Action $action) {
8    $action->doSomethingElse();
9});