I'm using the AppServiceProvider to share specific admin data with all related views.
Now I'd like to share admin data also with all admin related Controllers to replace Auth::guard('admin')->user()->firstname by $admin->firstname
.
$id = Auth::guard('admin')->user()->id;
$admin = Admin::findOrFail($id)->first();
How can I share this piece of code with all related Controllers to get for example admin firstname
via $admin->firstname
?
I would go about creating a global middleware
php artisan make:middleware AdminCarrier
In the middleware, you can add the $admin
variable to the $request
bag and access it via the Controller.
class AdminCarrier
{
public function handle($request, Closure $next)
{
$id = Auth::guard('admin')->user()->id;
$admin = Admin::findOrFail($id)->first();
$request->request->add(['admin' => $admin]);
return $next($request);
}
}
In the controller, you can access it via:
$request->admin
Make sure the middleware is global by registering it at Http/Kernel.php