Add conditionable behavior to your own classes

You can use the Conditionable Trait to avoid using if/else and promote method chaining.

1<?php
2 
3namespace App\Services;
4 
5use Illuminate\Support\Traits\Conditionable;
6 
7class MyService
8{
9 use Conditionable;
10 
11 // ...
12}
1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Http\Controllers\Controller;
6use App\Http\Requests\MyRequest;
7use App\Services\MyService;
8 
9class MyController extends Controller
10{
11 public function __invoke(MyRequest $request, MyService $service)
12 {
13 // Not good
14 $service->addParam($request->param);
15 
16 if ($request->has('something')) {
17 $service->methodToBeCalled();
18 }
19 
20 $service->execute();
21 // ---
22 
23 // Better
24 $service->addParam($request->param)
25 ->when($request->has('something'), fn ($service) => $service->methodToBeCalled())
26 ->execute();
27 // ---
28 
29 // ...
30 }
31}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord