Bump.
Wildcard Route
Hello everyone,
I would like to know how to implement a wildcard route which able to handle a different level of URL path and display the correct information and views layout.
Example my path can be something like this,
/
/category
/category/product
/category/product/1
/cart
/checkout/address
/checkout/payment
/about-us
...
Web.php
Route::get('/', 'Frontend\HomeController@index');
Route::get('/{path}', 'Frontend\HomeController@handler')->where(['path' => '.*']);
RouteController
// Explode the path into an array
$path = explode('/', $path);
// Calculate the level of the path
switch (count($path)) {
case 1:
if (
$path[0] == "cart"
) {
return view('frontend.' . $path[0]);
}
break;
case 2:
return view('frontend.' . $path[0] . '.' . $path[1]);
break;
case 3:
return view('frontend.' . $path[0] . '.' . $path[1] . '.' . $path[1]);
break;
default:
return view('frontend.home', ['universes' => $this->universes]);
break;
}
Am I doing this correct? Is there any tutorial I can learn how to create a proper wildcard route?
Hello Weehong
Try this in your web.php
Route::get('/test/{wildcard}', function(){
return "First";
});
Route::get('/test/second', function(){
return "Second";
});
Now if you go to http://127.0.0.1:8000/test/second, You will see that it returns "First"
Which means that when you have a url, laravel will look into your web.php and match the FIRST correct pattern and ignore following
If you want to go ahead with your wildcard route, be sure to put it AT THE BOTTOM of your web.php file
Example:
/
/cart
/checkout/address
/checkout/payment
/about-us
/* AT THE BOTTOM */
/{category}/product/1
/{category}/product
/{category}
In this way, when you have /cart or /about-us, you can use normal routing. I assume you know how to do this part.
But for wildcard, you can handle just like in your code example. But now you only need to handle your special cases. I'm assuming you are using a database or similar to make it dynamic.
However, I would still express concern like others showed above. This is not really a recommended way.
Whether you store it in database or web.php, you still have to write it down somewhere. However, if it fits YOUR need , i hope this helps :)
Please or to participate in this conversation.