Laravel Tutorials

Streamline Conditional Logic with Laravel's Fluent Conditionable Trait

Published
Streamline Conditional Logic with Laravel's Fluent Conditionable Trait image

Laravel enhances code readability by adding the Conditionable trait to the Fluent class, enabling developers to execute conditional operations through a fluent interface that maintains method chaining without breaking code flow.

The Conditionable trait allows conditional execution of operations using when() and unless() methods, transforming traditional if-else statements into expressive, natural-language-like code. This approach prioritizes readability while maintaining functional elegance.

Consider the difference between traditional and fluent conditional approaches:

Traditional Conditional Logic:

$config = Fluent::make([
    'app_name' => 'TaskManager',
    'debug_mode' => true,
    'features' => 12,
]);
 
if (auth()->isPremium()) {
    $config = $config->set('tier', 'premium');
} else {
    $config = $config->forget('features');
}

Fluent Conditional Logic:

$config = Fluent::make([
    'app_name' => 'TaskManager',
    'debug_mode' => true,
    'features' => 12,
])->when(auth()->isPremium(), function (Fluent $input) {
    return $input->set('tier', 'premium');
})->unless(auth()->isPremium(), function (Fluent $input) {
    return $input->forget('features');
});

The fluent approach maintains operational flow without interrupting method chains. It reads naturally: "Create a Fluent object with these properties, when user is premium add the premium tier, unless user is premium remove the features count."

This pattern proves particularly valuable when preparing complex data structures:

use Illuminate\Support\Fluent;

class ProductResource
{
    public function toArray($request)
    {
        $product = $this->resource;
        
        return Fluent::make([
            'id' => $product->id,
            'name' => $product->name,
            'price' => $product->price,
            'available_since' => $product->created_at->toDateString(),
        ])
            ->when($request->user()->can('view-analytics'), function (Fluent $data) use ($product) {
                return $data->set('view_count', $product->views()->count())
                            ->set('purchase_count', $product->orders()->count());
            })
            ->when($product->isOnSale(), function (Fluent $data) use ($product) {
                return $data->set('sale_price', $product->sale_price)
                            ->set('discount_percentage', $product->discount_rate);
            })
            ->unless($request->includesSensitiveData(), function (Fluent $data) {
                return $data->forget('cost_price')
                            ->forget('supplier_info');
            })
            ->when($product->hasReviews(), function (Fluent $data) use ($product) {
                return $data->set('average_rating', $product->averageRating())
                            ->set('review_count', $product->reviews()->count());
            })
            ->toArray();
    }
}

This approach enables building response data conditionally based on permissions, product states, and request parameters while preserving code flow and readability. Each condition clearly expresses its purpose without breaking the logical sequence of operations.

The Conditionable trait transforms complex conditional logic into expressive, maintainable code that communicates intent clearly while reducing cognitive load on developers reading and maintaining the codebase.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article
PIE 1.5 Changes PHP Extension Installs in CI image

PIE 1.5 Changes PHP Extension Installs in CI

Read article
Delete Expired Sessions in Laravel With a Scheduled Command image

Delete Expired Sessions in Laravel With a Scheduled Command

Read article
Pollora: Run WordPress Inside a Laravel Application image

Pollora: Run WordPress Inside a Laravel Application

Read article
Scheduled Session Garbage Collection in Laravel 13.39 image

Scheduled Session Garbage Collection in Laravel 13.39

Read article