自定义中间件检查模型自定义函数返回的值时出错 Laravel 5.1

Error on custom middleware checking the value returned on a Model custom Function Laravel 5.1

我有一个用于我的 Laravel 应用程序的帐户电子邮件确认,然后我想检查用户何时尝试登录,如果用户已经激活了他的帐户。

我发现了这个:https://laracasts.com/discuss/channels/general-discussion/how-to-test-if-a-user-which-tries-to-log-in-is-confirmed-yet

我有一个自定义模型函数 isActivated,它仅 return 用户模型上的状态属性(布尔类型,在西班牙语中名为 estado)。

在我的用户模型上:

public function isActivated()
{
    return $this->estado;
}

我创建了类似于 link 上面提供的建议的中间件,然后我在 App/Http/Kernel.php 中注册为中间件路由

当我将我的中间件分配给我的路由时出现问题(而不是在我的控制器中创建构造函数,我希望这个中间件只是在登录控制器的 post 请求时)。

当我尝试登录时出现错误:

Fatal Throwable Error: 
Fatal Error: Call to a member function isActivated() on null

我的中间件看起来和 link

完全一样
<?php

 namespace App\Http\Middleware;

 use Closure;
 use Illuminate\Contracts\Auth\Guard;

 class RedirectIfNotMailActivated
{
/**
 * The Guard implementation.
 *
 * @var Guard
 */
protected $auth;

/**
 * Create a new filter instance.
 *
 * @param  Guard  $auth
 * @return void
 */
public function __construct(Guard $auth)
{
    $this->auth = $auth;
}
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    if ( ! $this->auth->user()->isActivated()) {
        return redirect('/login')
            ->with('mensaje',
                   '¡Lo sentimos, no ha confirmado su cuenta aún!');
    } else {
        return $next($request);
    }
 }
}

有趣的部分:如果我在 App/Http/Middleware/Authenticate(auth middleware) 中添加我的中间件的 handle 函数的内容,然后我将一些路由分组并附加到这个中间件,这会按预期工作(不是允许未确认的用户登录)

问题是我在用户 table 中存在用户类型(管理员和客户)的多态关系,因此我将管理员控制面板附加并分组到 auth 中间件,因为我需要限制对控制的访问面板仅适用于经过身份验证的用户和管理员类型(不允许用于客户用户类型)。

限制仅适用于管理员用户类型。

当然,这让客户用户类型可以登录,因为无论他的帐户是否已确认,我都没有任何限制。

我哪里做错了... isActivated 模型函数在添加到 auth 中间件时工作正常,但当我在我的自定义中间件中使用相同的方法时却不行。

谢谢....

已编辑

我的中间件分配给我的登录控制器post方法

Route::post('/login', [
        'middleware' => 'activated.email',
        'uses' => 'loginController@store'
]);

PD:很抱歉 post 和糟糕的英语能力,这不是我的母语 :(

你的逻辑有问题。您的 login 路径不应受到激活用户的保护,因为中间件是在请求之前执行的,因此在您的情况下用户无法尝试登录并且您会收到错误消息那。

你可以做的是在 A​​uthenticate 中间件中添加你的 isActivated() 检查,这样你就会有一个登录用户并且 $this->auth->user() 赢了'为空。