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 →
Generate Laravel Validation Rules From a JSON Schema image

Generate Laravel Validation Rules From a JSON Schema

Read article
Laravel Suspicious Login: Detect and Block Risky Logins image

Laravel Suspicious Login: Detect and Block Risky Logins

Read article
Decide with Jev: Make Failed AI Requests Safe in Laravel image

Decide with Jev: Make Failed AI Requests Safe in Laravel

Read article
Black Friday: Learn the habits behind AI workflows that work image

Black Friday: Learn the habits behind AI workflows that work

Read article
Laravel Black Friday and Cyber Monday Deals 2026 image

Laravel Black Friday and Cyber Monday Deals 2026

Read article
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article