1

I am using Laravel 5.2 version, and I have tried to share data between all views, but for some reason I can't get it to work. In my Controller.php __construct function I have setup it up like this, but this is not working:

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;

class Controller extends BaseController
{
    use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        view()->share('user', Auth::user());
     }
}

I am trying to render that in my navigation partial like this:

<li>{{ $user->name }}</li>
Ludwig
  • 1,401
  • 13
  • 62
  • 125

2 Answers2

2

You should create service provider or use view composers for that.

Also, you don't need to create separate variable for Auth::user() or auth()->user(), because you already can use those in all views out of the box.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

Edit 2: For Security Reasons You can't get Auth in Controller.php, but you Can create CustomController.php that extents from Controller, and you other controllers must extends from CustomController, In Custom Controller you can use Auth, and Share $user with all views.

try this way and don't forget to use Auth;

View::share('user', Auth::user());

instead of your

view()->share('user', Auth::user());

And The Article that can help you

EDIT: I have tried it in my Laravel 5 App just type

 \View::share('user', Auth::user());

That's all.

Community
  • 1
  • 1
Rob
  • 127
  • 8