简体   繁体   English

Laravel控制器和视图中的全局变量

[英]Global variable in Laravel controllers and views

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. 我在Laravel 5.2中有一个带有auth的组中间件,我希望有一个全局变量$ current_user ,它必须可以在控制器和视图中直接访问。

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. 应用程序/ HTTP /控制器/ 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. 在您的控制器中,您只需使用$this->currentUser即可访问登录用户。 In your views you can just use $currentUser to access the logged in user. 在您的视图中,您只需使用$currentUser即可访问登录用户。 You only need to do this once in that one file because all of your controllers should extend Controller . 您只需要在该文件中执行一次,因为所有控制器都应该扩展Controller

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM