Maramal
Maramal

Reputation: 3475

Laravel Static Optional Routes

I am looking for a "quick" and "clean" solution to the usual http://project.name/products/total where total is optional.

I've tried so far this:

Route::get('products/{total?}', 'ProductController@get', function ($total = null) {});

And then $products = ($total == null) ? Product::all() : Product::count();

But this not only works with products/total but products/whatever. I think adding if($total = 'total') is not a good practice.

I want the last parameter to be static, I am not thinking straight. I guess I have to avoid defining two Routes (Route::get('products'... and Route::get('products/total'...

Laravel Documentation is not helping either. What am I doing wrong?

Upvotes: 0

Views: 174

Answers (2)

apokryfos
apokryfos

Reputation: 40680

If your routes are in reality doing different things (even if they are quite similar) then you should probably add two different routes.

Route::get('products', function () {
      Product::all() 
});

Route::get('products/total', function () {
      Product::count() 
});

Of course this does imply that if there's code that's shared between the two routes you can move it to its own helper function/class.

Upvotes: 1

Jonathon
Jonathon

Reputation: 16313

The cleaner way would probably be to have two separate routes. However, if you like you could add a constraint to your total parameter, to ensure it is exactly total if it is provided:

Route::get('products/{total?}', function ($total = null) {
    dd($total);
})->where(['total' => 'total']);

With this, you can hit products and $total will be null. You could hit products/total and $total will be 'total'. Finally, if you hit products/anythingelseatall you will see a 404.

Upvotes: 2

Related Questions