laravel 所有控制器和视图的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25189427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:40:50  来源:igfitidea点击:

global variable for all controller and views

laravellaravel-4global-variables

提问by Deepak Goyal

In Laravel I have a table settings and i have fetched complete data from the table in the BaseController, as following

在 Laravel 中,我有一个表设置,我从 BaseController 中的表中获取了完整的数据,如下所示

public function __construct() 
{
    // Fetch the Site Settings object
    $site_settings = Setting::all();
    View::share('site_settings', $site_settings);
}

Now i want to access $site_settings. in all other controllers and views so that i don't need to write the same code again and again, so anybody please tell me the solution or any other way so i can fetch the data from the table once and use it in all controllers and view.

现在我想访问 $site_settings。在所有其他控制器和视图中,这样我就不需要一次又一次地编写相同的代码,所以请任何人告诉我解决方案或任何其他方式,以便我可以从表中获取一次数据并在所有控制器中使用它和看法。

采纳答案by The Alpha

At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):

首先,配置文件适用于这种情况,但您也可以使用另一种方法,如下所示(Laravel - 4):

// You can keep this in your filters.php file
App::before(function($request) {
    App::singleton('site_settings', function(){
        return Setting::all();
    });

    // If you use this line of code then it'll be available in any view
    // as $site_settings but you may also use app('site_settings') as well
    View::share('site_settings', app('site_settings'));
});

To get the same data in any controller you may use:

要在任何控制器中获取相同的数据,您可以使用:

$site_settings = app('site_settings');

There are many ways, just use one or another, which one you prefer but I'm using the Container.

有很多方法,只使用一种或另一种,你更喜欢哪一种,但我正在使用Container.

回答by ollieread

Okay, I'm going to completely ignore the ridiculous amount of over engineering and assumptions that the other answers are rife with, and go with the simple option.

好的,我将完全忽略其他答案充斥的大量过度工程和假设,并采用简单的选项。

If you're okay for there to be a single database call during each request, then the method is simple, alarmingly so:

如果您可以在每个请求期间进行单个数据库调用,那么该方法很简单,令人震惊的是:

class BaseController extends \Controller
{

    protected $site_settings;

    public function __construct() 
    {
        // Fetch the Site Settings object
        $this->site_settings = Setting::all();
        View::share('site_settings', $this->site_settings);
    }

}

Now providing that all of your controllers extend this BaseController, they can just do $this->site_settings.

现在,如果您的所有控制器都扩展了这个 BaseController,它们就可以执行$this->site_settings.

If you wish to limit the amount of queries across multiple requests, you could use a caching solution as previously provided, but based on your question, the simple answer is a class property.

如果您希望限制跨多个请求的查询数量,您可以使用之前提供的缓存解决方案,但根据您的问题,简单的答案是类属性。

回答by malhal

Use the Config class:

使用配置类:

Config::set('site_settings', $site_settings);

Config::get('site_settings');

http://laravel.com/docs/4.2/configuration

http://laravel.com/docs/4.2/configuration

Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.

在运行时设置的配置值只为当前请求设置,不会被带到后续请求中。

回答by Koushik Das

In Laravel, 5+ you can create a file in the config folder and create variables in that and use that across the app. For instance, I want to store some information based on the site. I create a file called siteVars.php, which looks like this

在 Laravel 5+ 中,您可以在 config 文件夹中创建一个文件并在其中创建变量并在整个应用程序中使用它。例如,我想根据站点存储一些信息。我创建了一个名为 的文件siteVars.php,它看起来像这样

<?php
return [
    'supportEmail' => '[email protected]',
    'adminEmail' => '[email protected]'
];

Now in the routes, controller, viewsyou can access it using

现在,在routes, 中controllerviews您可以使用

Config::get('siteVars.supportEmail')

In the views if I this

在意见中,如果我这个

{{ Config::get('siteVars.supportEmail') }}

It will give [email protected]

它会给 [email protected]

Hope this helps.

希望这可以帮助。

回答by nbsp

I see, that this is still needed for 5.4+ and I just had the same problem, but none of the answers were clean enough, so I tried to accomplish the availability with ServiceProviders. Here is what i did:

我明白了,5.4+ 仍然需要这个,我只是遇到了同样的问题,但没有一个答案足够干净,所以我尝试使用ServiceProviders. 这是我所做的:

  1. Created the Provider SettingsServiceProvider
  1. 创建了提供者 SettingsServiceProvider
    php artisan make:provider SettingsServiceProvider
  1. Created the Model i needed (GlobalSettings)
  1. 创建了我需要的模型 ( GlobalSettings)
    php artisan make:model GlobalSettings
  1. Edited the generated registermethod in \App\Providers\SettingsServiceProvider. As you can see, I retrieve my settings using the eloquent model for it with Setting::all().
  1. 中编辑了生成的register方法\App\Providers\SettingsServiceProvider。如您所见,我使用 eloquent 模型为它检索了我的设置Setting::all()
 

    public function register()
    {
        $this->app->singleton('App\GlobalSettings', function ($app) {
            return new GlobalSettings(Setting::all());
        });
    }

 
  1. Defined some useful parameters and methods (including the constructor with the needed Collectionparameter) in GlobalSettings
  1. 在中定义了一些有用的参数和方法(包括带有所需Collection参数的构造函数)GlobalSettings
 

    class GlobalSettings extends Model
    {
        protected $settings;
        protected $keyValuePair;

        public function __construct(Collection $settings)
        {
            $this->settings = $settings;
            foreach ($settings as $setting){
                $this->keyValuePair[$setting->key] = $setting->value;
            }
        }

        public function has(string $key){ /* check key exists */ }
        public function contains(string $key){ /* check value exists */ }
        public function get(string $key){ /* get by key */ }
    }

 
  1. At last I registered the provider in config/app.php
  1. 最后我注册了提供者 config/app.php
 

    'providers' => [
        // [...]

        App\Providers\SettingsServiceProvider::class
    ]

 
  1. After clearing the config cache with php artisan config:cacheyou can use your singleton as follows.
  1. 清除配置缓存后,php artisan config:cache您可以按如下方式使用您的单例。
 

    $foo = app(App\GlobalSettings::class);
    echo $foo->has("company") ? $foo->get("company") : "Stack Exchange Inc.";

 

You can read more about service containers and service providers in Laravel Docs > Service Container and Laravel Docs > Service Providers.

您可以在 Laravel Docs > Service Container 和 Laravel Docs > Service Providers 中阅读有关服务容器和服务提供者的更多信息。

This is my first answer and I had not much time to write it down, so the formatting ist a bit spacey, but I hope you get everything.

这是我的第一个答案,我没有太多时间写下来,所以格式有点空洞,但我希望你能得到一切。



I forgot to include the bootmethod of SettingsServiceProvider, to make the settings variable global available in views, so here you go:

我忘了包括 , 的boot方法SettingsServiceProvider,以使设置变量在视图中全局可用,所以你去吧:

 

    public function boot(GlobalSettings $settinsInstance)
    {
        View::share('globalsettings', $settinsInstance);
    }

 

Before the boot methods are called all providers have been registered, so we can just use our GlobalSettingsinstance as parameter, so it can be injected by Laravel.

在调用引导方法之前,所有提供程序都已注册,因此我们可以使用我们的GlobalSettings实例作为参数,因此它可以被 Laravel 注入。

In blade template:

在刀片模板中:

 

    {{ $globalsettings->get("company") }}

 

回答by Gediminas

Most popular answers here with BaseController didn't worked for me on Laravel 5.4, but they have worked on 5.3. No idea why.

BaseController 中最受欢迎的答案在 Laravel 5.4 上对我不起作用,但它们在 5.3 上起作用。不知道为什么。

I have found a way which works on Laravel 5.4 and gives variables even for views which are skipping controllers. And, of course, you can get variables from the database.

我找到了一种适用于 Laravel 5.4 的方法,甚至可以为跳过控制器的视图提供变量。而且,当然,您可以从数据库中获取变量。

add in your app/Providers/AppServiceProvider.php

加入你的 app/Providers/AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Using view composer to set following variables globally
        view()->composer('*',function($view) {
            $view->with('user', Auth::user());
            $view->with('social', Social::all()); 
            // if you need to access in controller and views:
            Config::set('something', $something); 
        });
    }
}

credit: http://laraveldaily.com/global-variables-in-base-controller/

信用:http: //laraveldaily.com/global-variables-in-base-controller/

回答by Martin Carstens

In Laravel 5.1 I needed a global variable populated with model data accessible in all views.

在 Laravel 5.1 中,我需要一个全局变量,填充可在所有视图中访问的模型数据。

I followed a similar approach to ollieread's answer and was able to use my variable ($notifications) in any view.

我对 ollieread 的回答采用了类似的方法,并且能够在任何视图中使用我的变量 ($notifications)。

My controller location: /app/Http/Controllers/Controller.php

我的控制器位置:/app/Http/Controllers/Controller.php

<?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 App\Models\Main as MainModel;
use View;

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

    public function __construct() {
        $oMainM = new MainModel;
        $notifications = $oMainM->get_notifications();
        View::share('notifications', $notifications);
    }
}

My model location: /app/Models/Main.php

我的模型位置:/app/Models/Main.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class Main extends Model
{
    public function get_notifications() {...

回答by Rasim

View::share('site_settings', $site_settings);

Add to

添加

app->Providers->AppServiceProviderfile boot method

app->Providers->AppServiceProvider文件引导方法

it's global variable.

它是全局变量。

回答by spedley

In Laravel 5+, to set a variable just once and access it 'globally', I find it easiest to just add it as an attribute to the Request:

在 Laravel 5+ 中,只需设置一次变量并“全局”访问它,我发现将其作为属性添加到请求中最简单:

$request->attributes->add(['myVar' => $myVar]);

Then you can access it from any of your controllers using:

然后您可以使用任何控制器访问它:

$myVar = $request->get('myVar');

and from any of your blades using:

并从您的任何刀片使用:

{{ Request::get('myVar') }}

回答by Seb Barre

If you are worried about repeated database access, make sure that you have some kind of caching built into your method so that database calls are only made once per page request.

如果您担心重复访问数据库,请确保您的方法中内置了某种缓存,以便每个页面请求只调用一次数据库。

Something like (simplified example):

类似于(简化示例):

class Settings {

    static protected $all;

    static public function cachedAll() {
        if (empty(self::$all)) {
           self::$all = self::all();
        }
        return self::$all;
    }
}

Then you would access Settings::cachedAll()instead of all()and this would only make one database call per page request. Subsequent calls will use the already-retrieved contents cached in the class variable.

然后您将访问Settings::cachedAll()而不是all()每个页面请求只会进行一次数据库调用。后续调用将使用缓存在类变量中的已检索内容。

The above example is super simple, and uses an in-memory cache so it only lasts for the single request. If you wanted to, you could use Laravel's caching (using Redis or Memcached) to persist your settings across multiple requests. You can read more about the very simple caching options here:

上面的例子非常简单,并且使用了内存缓存,所以它只对单个请求有效。如果您愿意,您可以使用 Laravel 的缓存(使用 Redis 或 Memcached)来跨多个请求保存您的设置。您可以在此处阅读有关非常简单的缓存选项的更多信息:

http://laravel.com/docs/cache

http://laravel.com/docs/cache

For example you could add a method to your Settingsmodel that looks like:

例如,您可以向Settings模型添加一个方法,如下所示:

static public function getSettings() {
    $settings = Cache::remember('settings', 60, function() {
        return Settings::all();
    });
    return $settings;
}

This would only make a database call every 60 minutes otherwise it would return the cached value whenever you call Settings::getSettings().

这只会每 60 分钟进行一次数据库调用,否则无论何时调用Settings::getSettings().