本文介绍了Laravel 5.2根据条件将相同的路由分配给不同的控制器动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望根据用户类型将相同的路由路由到不同的控制器.
I wish to route the same route to different controller base on user type.
例如
if (Auth::check() && Auth::user()->is_admin) {
Route::get('/profile', 'AdminController@show');
} elseif (Auth::check() && Auth::user()->is_superadmin) {
Route::get('/profile', 'SuperAdminController@show');
}
但这是行不通的.
如何使它按我的意愿工作?
How can I make it works as what I want?
推荐答案
您可以这样做
Route::get('/profile', 'HomeController@profile'); // another route
控制器
public function profile() {
if (Auth::check() && Auth::user()->is_admin) {
$test = app('App\Http\Controllers\AdminController')->getshow();
}
elseif (Auth::check() && Auth::user()->is_superadmin) {
$test = app('App\Http\Controllers\SuperAdminController')->getshow();
// this must not return a view but it will return just the needed data , you can pass parameters like this `->getshow($param1,$param2)`
}
return View('profile')->with('data', $test);
}
但是我认为最好使用特征
But i think its better to use a trait
trait Show {
public function showadmin() {
.....
}
public function showuser() {
.....
}
}
然后
class HomeController extends Controller {
use Show;
}
然后您可以执行与上述相同的操作,而不是
Then you can do the same as the above but instead of
$test = app('App\Http\Controllers\AdminController')->getshow();// or the other one
使用此
$this->showadmin();
$this->showuser(); // and use If statment ofc
这篇关于Laravel 5.2根据条件将相同的路由分配给不同的控制器动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!