在laravel服务提供商中使用auth

ujw*_*kal 2 ioc-container laravel laravel-5

每当我试图使用\Auth::User()我得到非对象属性,因为Auth::guest()无论何时我在服务提供商中使用它都返回true

use Illuminate\Contracts\View\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\View\Factory;
use App\relations;
use App\User;
use DB;
use Illuminate\Support\Facades\Auth;

class RelationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        \Auth::User()->id;

        $relation_friend_for_logged_user = DB::select( DB::raw("SELECT * FROM users"));

        $value = "asd";

        // for injecting objct
        View()->share('count', $value);
    }
Run Code Online (Sandbox Code Playgroud)

但是,\Auth::guest()无论我是否登录,为什么返回true

dar*_*aim 9

您可能希望使用View Composer.据我所知,您的服务提供商启动方法中尚未提供经过身份验证的用户.

public function boot(Guard $auth) {
    view()->composer('*', function($view) use ($auth) {
        // get the current user
        $currentUser = $auth->user();

        // do stuff with the current user
        // ...

        // pass the data to the view
        $view->with('currentUser', $currentUser);
    });
}
Run Code Online (Sandbox Code Playgroud)

代码修改自https://laracasts.com/discuss/channels/general-discussion/how-do-i-get-the-current-authenticated-user-laravel-5