Sometimes, we needs to add multiple routes in our laravel application. Here we will create dynamic routes so we can use as many parameters.
First of all add the code given below in your routes file. we are using the laravel 5.5 so our routes file is web.php under routes directory.
Route::get('{slug?}', 'UriController')->name('page_url')->where('slug','.+');
Now create a controller file UriController.php under your controllers directory and add the code given below.
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
class UriController extends Controller
{
/**
* Show the page for the given slug.
*
* @param string $request uri
* @return Response
*/
public function __invoke(Request $request)
{
$request_path = $request->path();
$request_path_array = explode('/', $request_path);
}
}
Code Explanation:
We add a parameter {slug?} in our route and added the where condition. So, we can add as many parameters dynamically. You can also add any regular expression in where condition. Now your url will look like this https://example.com/parameter1/parameter2 and so on.
We have used the name method in our routes to access routes through name in our blade templates or controllers like this
route('page_url',['slug' => 'abc/123']);
Here we created a Single Action Controller UriController and we gets the uri in our __invoke method.
In our request method we have $request_path_array. So, we can loop through our dynamic parameters passed in url.
If you want do not want to apply particular uri to the route above then you can use the code given below which uses the all routes except the api in the routes.
Route::get('{slug?}', 'UriController')->name('page_url')->where('slug','^(?!api).*$');
If you want add prefix to your routes then you can use the code given below. Now your url will look like this https://example.com/your-prefix/parameter1/parameter2 and so on.
Route::prefix('your-prefix')->group(function () {
Route::get('{slug?}', 'UriController')->name('page_url')->where('slug','.+');
});
Thanks:)
Please give your suggestions :)
Top comments (0)