jasonb's avatar

can I access current user data in blade?

I want to access the user data, name for instance in my header.blade.php if the user is logged in. What is the simple solution?

I know I am asking basic questions but I am trying to learn. Thank you,

-J

0 likes
10 replies
fuelingtheweb's avatar
Level 31

You can call the Auth facade in your views.

{{ Auth::user()->name }}
28 likes
Penderis's avatar

You would use Auth::check() to see if user is authenticated, then Auth::id() or Auth::User()->username or other related data that is in the users table else you would have to send the user info to your view if you have a basic table but save personal infor on another table from your controller you would then

$userInfo = User::find(Auth::id())->with('personalInfo')->first();
return View::make('page')->with('userInfo',$userInfo);

//in your view then you have access to 
{{$userInfo->name }}
{{$userInfo->address}}
//the values from the table and related model.

1 like
dberry's avatar

I just add the following to the Authenticate middleware just before the return..

View::share([ 'currentUser' => $this->auth->user() ]);

Then it's available anywhere in my views.

4 likes
florenxe's avatar

This is what i am trying to achieve:

@section('title', '{{ Auth::user()->fullname }}')

I am trying to get the fullname of the currently logged in user and display it as the title of the view. This ofcourse wouldnt work. Please share with me the right way to go about this. thanks

1 like
huglester's avatar

Is there a way to bind $currentUser variable to views? using (for example) ViewCOmposers? becaues in view composers Auth::check() returns false, while if I do Auth::check() in view itself - it is ok :(

huglester's avatar

Btw, using the closure it did work:

view()->composer('*', function($view) {
            $view->with('currentUser', \Auth::user());
        });

Good luck!

mtzrmzia's avatar

where should i put it? in some function ?

Please or to participate in this conversation.