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();
$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?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.