Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
laravel 5-在RouteServiceProvider.php中使用Auth::check()_Php_Authentication_Laravel 5_Service Provider - Fatal编程技术网

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

laravel 5-在RouteServiceProvider.php中使用Auth::check(),php,authentication,laravel-5,service-provider,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)

我想在我的应用程序中检查未读消息,就像在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
数组中(在
illighted\Session\Middleware\StartSession
之后)


为什么不使用构造函数在
app/Http/Controllers/Controller.php
类中添加它,这样所有后续控制器都将运行代码,并且数据将在所有视图中可用。请确保通过
父项::u construct()调用它
我在
使用DispatchesCommands,validateRequests之后添加了
公共函数uuu construct(){..}
抽象类控制器中的code>。。这似乎有效,但我不确定这是否是正确的方法。我应该在哪里使用
parent::u construct()调用它?我不明白。它肯定与
RouteServiceProvider
无关,所以它不应该驻留在那里。我认为它更适合于为视图设置数据,这是由控制器来完成的。Put
parent::u construct()
\uu构造()
中。您可以在基本刀片布局上使用此方法或使用视图生成器。好的,我已将
父项::\uu构造()
放入控制器的
\uu构造()
中,这些控制器具有
\uu构造()
扩展
控制器
除了
Auth/PasswordController.php
之外,因为我不确定。。谢谢。当用户未登录时,将使用Auth/*控制器。所以他们不需要这些信息。这对我来说是一个很好的策略,可以在控制器的每个视图上加载数据。
<?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);
    }

}