drrqwokuz71031449
2017-05-30 15:46
浏览 33
已采纳

Laravel 5.4中的其他auth中间件

I want to add additional middleware to user model. User table has row 'approved' which is boolean (default is false). So when user logins - middleware should check if 'approved' is equal to true. If not, redirect to error page. What i got so far:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class ConfirmedMiddleware
{
    public function handle($request, Closure $next, $guard = null)
    {
        if(Auth::user()->approved != true){
            redirect('/error');
        }
        return $next($request);
    }
}

So far middleware attached here:

Route::get('/home', 'HomeController@index')->middleware('confirmed')->name('home');

However, it does not work. No errors as well.

图片转代码服务由CSDN问答提供 功能建议

我想在用户模型中添加其他中间件。 用户表有行'approved',它是boolean(默认为false)。 因此,当用户登录时 - 中间件应该检查​​'approved'是否等于true。 如果没有,请重定向到错误页面。 到目前为止我得到了什么:

 &lt;?php 
 
namespace App \ Http \ Middleware; 
 
use Closure; 
use Auth; 
 
class ConfirmedMiddleware \  n {
公共函数句柄($ request,Closure $ next,$ guard = null)
 {
 if if(Auth :: user() - &gt; approved!= true){
 redirect('/ error'  ); 
} 
返回$ next($ request); 
} 
} 
   
 
 

此处附带的中间件到目前为止:

  Route :: get('/ home','HomeController @ index') - &gt; middleware('confirmed') - &gt; name('home'); 
  <  / pre> 
 
 

但是,它不起作用。 没有错误。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duan0821 2017-05-30 15:54
    已采纳

    You're better off checking this when a user logins instead of using a middleware.

    Add this to the LoginController and perform any additional checks. This method will be called after the user successfully logs in.

    protected function authenticated($request, $user)
    {
        if($user->approved != true){
            return redirect('/error');
        }
    }
    

    If you still insist on using middleware, then make sure you add the middleware in Kernel.php

    Add this in app/Http/Kernel.php

    'confirmed' => \App\Http\Middleware\ConfirmedMiddleware::class,
    

    You're also missing the return in your redirect.

    public function handle($request, Closure $next, $guard = null)
    {
        if(Auth::user()->approved != true){
            return redirect('/error');
        }
    
        return $next($request);
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • drvfqr5609 2017-05-30 15:53

    You are missing the return in the redirect, It should be:

    return redirect('/error'); 
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题