πŸŽ‰πŸŽ‰ Larasense is officially launched πŸŽ‰πŸŽ‰
- Your Hub for Laravel News, Trends & Updates

Laravel Routing: Add Conditional Logic To Routes

laravel
release
routing
Nabil Hassen
Nabil Hassen
Dec 10, 2024
Laravel Routing
Last updated on Dec 10, 2024
Table of contents:

Introduction

Laravel 11.34.0 introduces the famous Conditionable trait to the route management allowing to add conditional logic when defining routes with the when() method. This enhancement allows developers to add conditional logic when defining routes, bringing more flexibility and clarity to route definitions. This feature was introduced by Boorinio and merged as part of pull request #53654.

The Problem It Solves

Previously, managing conditional logic for route definitions required more verbose or complex logic, often intertwined with other parts of your application. This new method simplifies the process, making route files cleaner and easier to understand.

How It Works

The when() method can be applied to define routes that load only when a given condition is true or to add any route related logic based on specified conditions. Here’s an example:

Route::middleware('shop')
->domain('{shop}.domain.com')
->when(App::isProduction(), function ($route) {
$route->whereIn('shop', app(ShopService::class)->getShopSlugs());
});

This improvement not only enhances readability but also allows developers to control route availability dynamically based on various application states or configurations.

Supported Versions

The when() method is available on routes starting from Laravel 11.34.0.

Nabil Hassen
Nabil Hassen
Full Stack Web Developer

Stay Updated.

I'll you email you as soon as new, fresh content is published.

Thanks for subscribing to my blog.

Latest Posts