2

我想检查我的应用程序中的未读消息,就像它在 laravel 4 的“过滤前”中一样。我已将其放入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;在文件顶部有一个。在这个文件中这通常是不可能的,还是一定是我犯的错误?

4

1 回答 1

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

于 2015-02-26T14:45:25.897 回答