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 Controller10{11 public function __invoke(MyRequest $request, MyService $service)12 {13 // Not good14 $service->addParam($request->param);15 16 if ($request->has('something')) {17 $service->methodToBeCalled();18 }19 20 $service->execute();21 // ---22 23 // Better24 $service->addParam($request->param)25 ->when($request->has('something'), fn ($service) => $service->methodToBeCalled())26 ->execute();27 // ---28 29 // ...30 }31}