我想检查我的应用程序中是否有未读消息,就像在 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;
。在这个文件中这通常是不可能的,或者它一定是我犯的错误?
最佳答案
您可以将其作为中间件,并添加到 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);
}
}
关于php - laravel 5 - 在 RouteServiceProvider.php 中使用 Auth::check(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28742457/