我试图在Middleware
中提供条件。
这是我的剧本
if (auth()->check() && auth()->user()->type == 'TP001') {
$menu->add("User Control",array('nickname' => "user",'class'=>'treeview'))
->append(' <b class="caret"></b>')
->prepend('<span class="glyphicon glyphicon-user"></span> ');
$menu->user->add('Daftar User','user/list');
$menu->user->add('Tipe User','user/type');
} else {
/* Some code here...*/
}
上面的脚本我不能看到带有条件的菜单,即使我已经使用'TP001'
登录(总是在其他地方),然后我尝试用这个修复我的代码
auth()->user()->isDeveloper()
我的模特
public function isDeveloper()
{
return ($this->type == 'TP001');
}
但仍然无法正常工作,有没有办法以正确的方式给出上述条件?提前致谢,抱歉我的英语不好。
我的内核
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\Frontend::class,
];
答案 0 :(得分:13)
中间件内核有你发布的$middleware
,中间件在每个请求中运行,但它们在路由中间件(你在路由定义中选择)之前运行。
你可能正在使用&#34; web&#34;中间件组。尝试在最后添加自定义中间件。我认为Laravel 5.4中的默认值是:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Frontend::class, // <-- your middleware at the end
],
'api' => [
'throttle:60,1',
'bindings',
],
];
通过这种方式,您知道您的中间件将在其他中间件之后运行(启动会话并检查身份验证的中间件)
答案 1 :(得分:3)
您可以将自定义中间件放在内核文件中受保护的$ routeMiddleware = []数组中,如下所示
$routeMiddleWare = ['frontend' => \App\Http\Middleware\Frontend::class]
在此之后,您将能够访问您的Auth :: check 并且不要忘了把
Route::group(['middleware' => ['frontend']], function() { // your routes will go here.. });
答案 2 :(得分:2)
您可以在任何刀片文件中获取当前用户:
{{ Auth::user()->name }}
在你的刀片中执行此操作:
@if(Auth::check() && Auth::user()->type == 'TP001')
/* Some code here...*/
@endif
在您的中间件中根据您的要求执行此操作!:
if (\Auth::check() && \Auth::user()->type == 'TP001') {
$menu->add("User Control",array('nickname' => "user",'class'=>'treeview'))
->append(' <b class="caret"></b>')
->prepend('<span class="glyphicon glyphicon-user"></span> ');
$menu->user->add('Daftar User','user/list');
$menu->user->add('Tipe User','user/type');
} else {
/* Some code here...*/
}