I have a group middleware with auth in Laravel 5.2, and I want to have a global variable $current_user that haves to be directly accesable in the controllers and in the views.
I don't want do this every time in the controller methods:
$current_user = Auth::user();
return view('account.view', ['current_user', $current_user]);
Is it possible to make a global variable for a authenticated user, what is the best option to do that?
This can be done quite easily. You should have a controller that every other controller extends.
app/Http/Controllers/Controller.php.
<?php
namespace App\Http\Controllers;
abstract class Controller
{
use DispatchesJobs, ValidatesRequests;
protected $currentUser;
public function __construct()
{
// Grab the logged in user if any and set it to this property.
// All extending classes should then have access to it.
$this->currentUser = \Auth::user();
// Share this property with all the views in your application.
view()->share('currentUser', $this->currentUser);
}
}
In your controllers you can just use $this->currentUser
to access the logged in user. In your views you can just use $currentUser
to access the logged in user. You only need to do this once in that one file because all of your controllers should extend Controller
.
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.