Skip to main content
Quick Tip

Add conditionable behavior to your own classes

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

namespace App\Services;
 
use Illuminate\Support\Traits\Conditionable;
 
class MyService
{
use Conditionable;
 
// ...
}
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Http\Requests\MyRequest;
use App\Services\MyService;
 
class MyController extends Controller
{
public function __invoke(MyRequest $request, MyService $service)
{
// Not good
$service->addParam($request->param);
 
if ($request->has('something')) {
$service->methodToBeCalled();
}
 
$service->execute();
// ---
 
// Better
$service->addParam($request->param)
->when($request->has('something'), fn ($service) => $service->methodToBeCalled())
->execute();
// ---
 
// ...
}
}

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

Laravel Modules and DDD

16 lessons
1 h 59 min

PhpStorm Junie AI for Laravel Projects: Crash Course

7 lessons
36 min

NativePHP: Build Mobile App with Laravel

11 lessons
2 h 2 min read

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.