Laravel 5.2在发送/ root之前检查条件

时间:2016-08-07 21:00:33

标签: php laravel

我似乎记得在以前版本的laravel中你可以设置一些在根被击中之前触发的逻辑。我要做的是:

if(Auth::check())
{
    if(!Auth::user()->email || is_null(Auth::user()->email))
    {
        return redirect('/dashboard')->with('error', 'You have not provided an email address');
    }
}

原因是我有社交登录和Twitter登录不提供电子邮件地址也没有Facebook登录。

如果您能想到比将用户重定向到仪表板更好的选择并添加电子邮件表格,请分享,因为在注册时我会通过事件处理程序和监听器发送欢迎电子邮件,这样可以节省我的费用触发事件之前控制器中的逻辑。

1 个答案:

答案 0 :(得分:1)

您可以添加执行此检查的其他middleware,也可以将其添加为应用程序现有Authenticate中间件中的另一个条件。

以下是Laravel 5.2中的默认Authenticate中间件,并添加了您的代码。 (您应该能够在app/Http/Middleware/Authenticate.php中找到此文件。)

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Authenticate
{
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            }
            return redirect()->guest('login');
        }

        /* YOUR ADDED CODE STARTS HERE */

        // Note that you don't need to call `Auth::check` because
        // `Auth::guest` has already been called above and has returned
        // `false` in order to get here.

        if(!Auth::user()->email || is_null(Auth::user()->email))
        {
            return redirect('/dashboard')->with('error', 'You have not provided an email address');
        }

        /* YOUR ADDED CODE ENDS HERE   */

        return $next($request);

    }

}