2016-01-18 52 views
2

我已經嘗試在構造函數中注入Guard守護進程,我嘗試過四處移動。但是當用戶登錄時 - Auth :: check()返回false。Auth :: check在AppServiceProvider中返回false

在其他文件(全局中間件除外)Auth :: check()工作正常。 在中間件 - 移動Auth Check到頂部有助於緩解問題。在這種情況下 - 它不起作用。

附加信息:此應用程序已從4.2升級。以前它使用Confide。

<?php 

namespace App\Providers; 

use Illuminate\Support\Facades\Auth; 
use Illuminate\Support\ServiceProvider; 

class AppServiceProvider extends ServiceProvider 
{ 

     /** 
    * Bootstrap any application services. 
    * 
    * @return void 
    */ 
    public function boot() 
    { 
     if(Auth::check()) 
     { 
      $user = Auth::user(); 
      $messages=Message::where('read',0); 
      $messages->where(function ($query) use ($user) { 
       $query->where('to',$user->id)->orwhere('from',$user->id); 
      }); 
      $message_unread= $messages->count(); 

      $new_notifications= Notification::where('user_id',$user->id)->where('viewed',0)->count();    
     } 
     else 
     { 
      $message_unread=0; 
      $new_notifications=8888888; 

//其888888用於測試目的。

 } 

     view()->share(([ 
      'message_unread'=>$message_unread, 
      'new_notifications'=>$new_notifications 
     ])); 
    } 

    /** 
    * Register any application services. 
    * 
    * @return void 
    */ 
    public function register() 
    { 
     // 
    } 
} 
+0

[Auth class和auth()函數的可能重複不會在Eloquent模型中工作。 (Laravel 5)](http://stackoverflow.com/questions/34835200/auth-class-and-auth-function-doesnt-works-in-eloquent-model-laravel-5) –

+0

我會檢查出來。謝謝。 –

+0

不要刪除此問題 –

回答

1

您應該將此代碼移到控制器層。 boot Laravel的ServiceProviders方法用於引導服務,而不是執行業務邏輯。

+0

這是一個可能的解決方案。正如托馬斯金解釋說,這樣做是不可能的。但我在所有視圖中都需要這些數據。我有什麼選擇? –

+0

看看https://laravel.com/docs/5.1/views#view-composers –

+0

謝謝!解決我的視圖作曲家的幫助。 –

1

您需要在在的ServiceProvider類的頂部,從使用的View Composer可使用auth

use Auth; 

而不是

use Illuminate\Support\Facades\Auth; 
0

除此之外,您還可以使用它後處理中間件會話變量已加載:

<?php 
namespace App\Http\Middleware; 

use Closure; 
use Illuminate\Contracts\Auth\Guard; 

class SetViewVariables 
{ 
    protected $auth; 

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

    public function handle($request, Closure $next) 
    { 
     $user = $this->auth->user(); 
     view()->share('user', $user); 

     return $next($request); 
    } 

} 
相關問題