laravel 5 - 在RouteServiceProvider.php中使用Auth :: check()

时间:2015-02-26 12:26:44

标签: php authentication laravel-5 service-provider

我想检查我的应用中的未读消息,就像它在laravel 4中的“before filter”中一样。我已将其放入RouteServiceProvider.php文件中的启动函数中:

$unread_messages = 0;

if(Auth::check())
{
    $unread_messages = Message::where('owner',Auth::user()->id)
                                ->where('read',0)
                                ->count();
}

View::share('unread_messages',$unread_messages);

看来,我不能在那里使用Auth::check()。我已登录,但未使用if子句中的代码。该应用已命名,我在文件顶部有一个use Auth;。这个文件通常不可能,或者它必须是我犯的错误吗?

1 个答案:

答案 0 :(得分:2)

您可以将其作为中间件,并添加到App\Http\Kernel::$middleware数组(Illuminate\Session\Middleware\StartSession之后)。

<?php namespace App\Http\Middleware;

use Closure;
use App\Message;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\View\Factory;

class UnreadMessages 
{
    protected $auth;
    protected $view;

    public function __construct(Guard $auth, Factory $view)
    {
        $this->auth = $auth;
        $this->view = $view;
    }

    public function handle($request, Closure $next)
    {
        $unread = 0;
        $user = $this->auth->user();

        if (! is_null($user)) {
            $unread = Message::where('user_id', $user->id)
                          ->where('read', 0)
                          ->count();
        }

        $this->view->share('unread_messages', $unread);

        return $next($request);
    }

}

进一步阅读http://laravel.com/docs/5.0/middleware