How can I do variable/wildcard routes in Laravel?

陌路散爱 提交于 2019-12-01 17:46:50
Mike

To do this, you need to load an instance of app() and then call make('Controller') method as well as callAction. Full route below:

Route::any('{slug}', function($slug){
    $url = \App\Url_slug::where('url_slug', $slug)->first();
    if($url->count()){
        $app = app();

        switch($url->url_type){
            case 'product':
                $controller = $app->make('App\Http\Controllers\ProductController');
                break;
            case 'category':
                $controller = $app->make('App\Http\Controllers\CategoryController');
                break;
            case 'page':
                $controller = $app->make('App\Http\Controllers\PageController');
                break;
        }
        return $controller->callAction('view', ['url_slug' => $url->url_slug, 'url_slug_id' => $url->id]);
    } else {
        abort(404);
    }
});

You can simply resolve a controller instance from the service container, and call methods on that:

return app('App\Http\Controllers\ProductController')->show($product);

This will call the ProductController@show action, pass whatever is in $product as a parameter, and return the rendered Blade template.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!