在 laravel 服务提供商中使用身份验证

using auth in laravel service provider

每当我尝试使用 \Auth::User() 我得到的不是对象 属性 因为我的 Auth::guest() returns 每当我在服务提供商

中使用它们时都是真的
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);
    }

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

都返回 true

您可能想为此使用 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);
    });
}

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