Sometimes, we need to add multiple routes to our Laravel application. Here, we will create dynamic routes so that we can use as many parameters as possible.

First add the code given below to your routing file. We are using laravel 5.5, so our routing file is web.php in the routing directory

Route::get('(slug?)','UriController')->name('page_url')->where('slug','.+');

Now create a controller file UriController.php in your controller 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 description

We added a parameter {slug?} and added a where condition to the route. Therefore, we can dynamically add as many parameters as possible. You can also add any regular expression in the where condition. Now your URL will look like the following https://example.com/parameter1/parameter2 etc.

We use the name method in the routing to access the routing through the name in the blade template or controller, as shown below

route('page_url',['slug' =>'abc/123']);

Here we create a Single Action Controller UriController and get the uri in our __invoke method.

In our request method, we have $request_path_array. Therefore, we can traverse the dynamic parameters passed in url.

If you don’t want to apply a specific uri to the above route, then you can use the code given below, which uses all routes except api in the route

Route::get('(slug?)','UriController')->name('page_url')->where('slug','^(?!api).*$');

If you want to add a prefix to the route, you can use the code given below. Now your URL will look like the following https://example.com/your-prefix/parameter1/parameter2

Route::prefix('your-prefix')->group(function () {

    Route::get('(slug?)','UriController')->name('page_url')->where('slug','.+');

});
点赞(0)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部