简体   繁体   中英

get loggedIn user in View Composer not working(Sentinel - Laravel 5.4)

I am using Sentinel in Laravel 5.4. What I am trying to do is: get logged user detail but Sentinel::getUser() returns null . For this process, I have seen this instruction in this answer . I am following using View Composer method.

Steps I have done

I have created a file ViewComposerServiceProvider inside Providers folder. It looks like:

public function boot()
    {
        $user      = Sentinel::getUser(); //<<-- main error: dd($user) returns empty
       $userDetail = UsersDetail::where('user_id', $user->id)->firstOrFail();

       if ( is_null ($userDetail) ) {
           $userDetail = new UsersDetail;
       }

       view()->composer('backend.*', function($view) {
           $view->with('userDetail', $userDetail);
           //$view->with('userDetail', 'Test'); //this works fine
       });
    }

Then, I register this provider in config/app.php Providers array as App\\Providers\\ViewComposerServiceProvider::class,

When, I pass other variables in userDetail , it's working perfectly. But, I cannot get the logged in user detail. Am I missing something?

Following the first solution from this answer also seems not working since, construct are run prior to the Middleware. Any help please.

Go to app\\Providers\\AppServiceProvider.php Then your serviceProvider.php boot method like below

public function boot()
{

 $user      = Sentinel::getUser(); //<<-- main error: dd($user) returns empty
       $userDetail = UsersDetail::where('user_id', $user->id)->firstOrFail();

       if ( is_null ($userDetail) ) {
           $userDetail = new UsersDetail;
       }

    View::composer('userDetail', function($view) use($userDetail ) {
    $view->with('userDetail ',$userDetail );
    });
}

Then your userDetail.blade.php you can access userDetail data like this

{{ $userDetail }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM