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

标签 php authentication laravel-5 service-provider

我想检查我的应用程序中是否有未读消息,就像在 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);
    }

}

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

关于php - laravel 5 - 在 RouteServiceProvider.php 中使用 Auth::check(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28742457/

相关文章:

php - 带数组元素的全文搜索 pdo

cordova - 如何从 Cordova Azure 验证应用程序查询 Azure Web API

c# - ASP.NET Core 2.0 预览版 1 : How to set up Cookie Authentication with custom login path

php - App\Providers\AppServiceProvider::App\Providers\{closure}() 缺少参数 2

php - SoapFault 异常 : Could not connect to host

php - 将自动递增的变量名插入数据库

authentication - Dockerfile 中的 Subversion 导出/结帐而不在屏幕上打印密码

javascript - 如何在 laravel 5 上获取 Bootstrap Modal 数据

php - Laravel 不会删除目录

php - Laravel DataTables Yajrabox 不显示数据