Create global variable for authenticated user in laravel 5.4

时间:2018-07-24 10:10:40

标签: php laravel-5.4

In laravel 5.4 after logged in I can access Auth::user() in each controller. but I want to make it as global variable that can be use in all controllers and views.

After google I tested following codes. 1) AppServiceProvider.php

public function boot()
{     
    View::share('currentUser', Auth::user()); 
}

But can not access in view.

2) app\Http\Controllers\Controller.php

private $user;
private $signed_in;

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->user = Auth::user();
        $this->signed_in = Auth::check();

        view()->share('signed_in', $this->signed_in);
        view()->share('user', $this->user);

        return $next($request);
    });

}

But can not access in view.

can anyone help thanks in advance.

1 个答案:

答案 0 :(得分:1)

我用第二种方法得到了解决方案。

2)app \ Http \ Controllers \ Controller.php

此控制器是基本控制器

private $user;
private $signed_in;

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->user = Auth::user();
        $this->signed_in = Auth::check();

        view()->share('signed_in', $this->signed_in);
        view()->share('user', $this->user);

        return $next($request);
    });

}

我必须在每个控制器构造函数中放置以下代码parent::__construct();

例如:

class StatusController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');

        parent::__construct();
    }
}

现在我可以在任何视图中访问

{{ $user->user_id }}