2

I want to be able to get a logged in user's details in my views. E.g {{ $user->email }}.

Here's my Controller.php:

public $view_data = array();

public function __construct()
{
    $this->middleware('auth');
    $this->view_data['user'] = Auth::user();
}

$user in my views return NULL. Am I missing something?

Nicholas Kajoh
  • 1,451
  • 3
  • 19
  • 28

4 Answers4

2

It is already available in all views by default via:

Auth::user()
auth()->user()
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

You can directly access loggedIn user in your views via following methods:

{!! Auth::user()->name !!}
{!! auth()->user()->name !!}
{!! access()->user()->name !!}
Balraj Allam
  • 611
  • 6
  • 24
0

{{ \Auth::user() }} {{ \Auth::user()['email'] }}

0

Laravel already provide this service after you logged in. Just simply write:

{{ Auth::user()->email }}
{{ auth()->user()->email }}

You can also use ServiceProvider for all views:

create service provider: php artisan make:provider UserServiceProvider

Go to

app\providers\UserServiceProvider.php

<?php

namespace App\Providers;

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

class UserServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */

    public function boot()
    { 
        if(Auth::check()){
            $user= Auth::user();
            View::share('user', $user);
        }
    }

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

Than register this service provider inside the config\app.php

App\Providers\UserServiceProvider::class,

Now user object available for all view you just simply write:

{{ $user->email }} 
{{ $user->username }}

Laravel Sharing Data With All Views