如何在Laravel中进行变量/通配符路由? [英] How can I do variable/wildcard routes in Laravel?
问题描述
我正在使用Laravel 5,并且需要执行通配符路由,根据从数据库中提取的URL类型将用户发送到其他控制器.
I am using Laravel 5 and need to do a wildcard route, sending the user to different controllers based on the URL type, pulled in from the database.
我需要检查数据库中的URL slug,然后根据数据库中保存的slug类型加载相关的控制器/方法.我正在为最后一部分而苦苦挣扎,这是将用户发送到相关的控制器.以下是我的路线:
I need to check the URL slug in the database, and then load the relevant controller/method based on the slug type, held in the database. I am struggling with the final part, which is sending the user to the relevant controller. Below is my route:
Route::any('{slug}', function($slug){
$url = \App\Url_slug::where('url_slug', $slug)->first();
if($url->count()){
switch($url->url_type){
case 'product':
// SEND USER TO PRODUCT CONTROLLER
break;
case 'category':
// SEND USER TO CATEGORY CONTROLLER
break;
case 'page':
// SEND USER TO PAGE CONTROLLER
break;
}
} else {
abort(404);
}
});
为了将用户发送到相关控制器,我需要用什么替换注释?
What do I need to replace the comments with in order the send the user to the relevant controller?
推荐答案
为此,您需要加载app()
的实例,然后调用make('Controller')
方法和callAction
.下方的完整路线:
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);
}
});
这篇关于如何在Laravel中进行变量/通配符路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!