php 如何将数据传递给 Laravel 5 中的所有视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28608527/
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-08-25 23:59:06  来源:igfitidea点击:

How to pass data to all views in Laravel 5?

phplaravellaravel-5

提问by Ragnarsson

I want to have some default data accessible in all views in my Laravel 5 application.

我希望在我的 Laravel 5 应用程序的所有视图中都可以访问一些默认数据。

I have tried to search for it but only find results for Laravel 4. I have read the documentation 'Sharing Data With All Views' herebut I can't understand what to do. Where should the following code be placed?

我试图搜索它,但只找到 Laravel 4 的结果。我在这里阅读了文档“与所有视图共享数据” 但我不明白该怎么做。下面的代码应该放在哪里?

View::share('data', [1, 2, 3]);

Thanks for your help.

谢谢你的帮助。

回答by Safoor Safdar

This target can achieve through different method,

这个目标可以通过不同的方法实现,

1. Using BaseController

1. 使用 BaseController

The way I like to set things up, I make a BaseControllerclass that extends Laravel's own Controller, and set up various global things there. All other controllers then extend from BaseControllerrather than Laravel's Controller.

我喜欢设置的方式,我创建了一个BaseController扩展 Laravel 自己的类Controller,并在那里设置各种全局的东西。所有其他控制器然后从而BaseController不是 Laravel 的控制器扩展。

class BaseController extends Controller
{
  public function __construct()
  {
    //its just a dummy data object.
    $user = User::all();

    // Sharing is caring
    View::share('user', $user);
  }
}

2. Using Filter

2. 使用过滤器

If you know for a fact that you want something set up for views on every request throughout the entire application, you can also do it via a filter that runs before the request — this is how I deal with the User object in Laravel.

如果你知道你想要为整个应用程序中的每个请求的视图设置一些东西,你也可以通过在请求之前运行的过滤器来实现——这就是我在 Laravel 中处理 User 对象的方式。

App::before(function($request)
{
  // Set up global user object for views
  View::share('user', User::all());
});

OR

或者

You can define your own filter

您可以定义自己的过滤器

Route::filter('user-filter', function() {
    View::share('user', User::all());
});

and call it through simple filter calling.

并通过简单的过滤器调用来调用它。

Update According to Version 5.*

根据版本 5.* 更新

3. Using Middleware

3. 使用中间件

Using the View::sharewith middleware

使用View::sharemiddleware

Route::group(['middleware' => 'SomeMiddleware'], function(){
  // routes
});



class SomeMiddleware {
  public function handle($request)
  {
    \View::share('user', auth()->user());
  }
}

4. Using View Composer

4. 使用 View Composer

View Composer also help to bind specific data to view in different ways. You can directly bind variable to specific view or to all views. For Example you can create your own directory to store your view composer file according to requirement. and these view composer file through Service provide interact with view.

View Composer 还有助于绑定特定数据以不同方式查看。您可以直接将变量绑定到特定视图或所有视图。例如,您可以根据需要创建自己的目录来存储您的视图作曲家文件。并且这些视图作曲家文件通过 Service 提供与视图的交互。

View composer method can use different way, First example can look alike:

查看 composer 方法可以使用不同的方式,第一个示例看起来很像:

You could create an App\Http\ViewComposersdirectory.

你可以创建一个App\Http\ViewComposers目录。

Service Provider

服务提供者

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
    public function boot() {
        view()->composer("ViewName","App\Http\ViewComposers\TestViewComposer");
    }
}

After that, add this provider to config/app.php under "providers" section.

之后,将此提供程序添加到“提供程序”部分下的 config/app.php。

TestViewComposer

测试视图编辑器

namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;

class TestViewComposer {

    public function compose(View $view) {
        $view->with('ViewComposerTestVariable', "Calling with View Composer Provider");
    }
}

ViewName.blade.php

视图名称.blade.php

Here you are... {{$ViewComposerTestVariable}}

This method could help for only specific View. But if you want trigger ViewComposer to all views, we have to apply this single change to ServiceProvider.

此方法仅适用于特定视图。但是如果你想对所有视图触发 ViewComposer,我们必须将这个单一的改变应用到 ServiceProvider。

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider {
    public function boot() {
        view()->composer('*',"App\Http\ViewComposers\TestViewComposer");
    }
}

Reference

参考

Laravel Documentation

Laravel 文档

For Further Clarification Laracast Episode

进一步澄清Laracast 插曲

If still something unclear from my side, let me know.

如果我这边还有不清楚的地方,请告诉我。

回答by Marwelln

You can either create your own service provider(ViewServiceProvidername is common) or you can use the existing AppServiceProvider.

您可以创建自己的服务提供者ViewServiceProvider名称很常见),也可以使用现有的AppServiceProvider.

In your selected provider, put your code in the boot method.

在您选择的提供程序中,将您的代码放在引导方法中。

public function boot() {
    view()->share('data', [1, 2, 3]);
}

This will make a $datavariable accessible in all your views.

这将使$data您可以在所有视图中访问变量。

If you rather want to use the facade instead of the helper, change view()->to View::but don't forget to have use View;at the top of your file.

如果您更愿意使用外观而不是助手,请更改view()->View::但不要忘记use View;在文件顶部使用。

回答by Stan Smulders

I found this to be the easiest one. Create a new provider and user the '*'wildcard to attach it to all views. Works in 5.3 as well :-)

我发现这是最简单的一种。创建一个新的提供者并使用'*'通配符将其附加到所有视图。也适用于 5.3 :-)

<?php

namespace App\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function ($view)
        {
            $user = request()->user();

            $view->with('user', $user);
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

回答by Reza Shadman

The best way would be sharing the variable using View::share('var', $value);

最好的方法是使用共享变量 View::share('var', $value);

Problems with composing using "*":

组合使用的问题"*"

Consider following approach:

考虑以下方法:

<?php
// from AppServiceProvider::boot()
$viewFactory = $this->app->make(Factory::class);

$viewFacrory->compose('*', GlobalComposer::class);

From an example blade view:

从示例刀片视图:

  @for($i = 0; $i<1000; $i++)
    @include('some_partial_view_to_display_i', ['toDisplay' => $i])
  @endfor

What happens?

发生什么了?

  • The GlobalComposerclass is instantiated 1000times using App::make.
  • The event composing:some_partial_view_to_display_iis handled 1000times.
  • The composefunction inside the GlobalComposerclass is called 1000 times.
  • GlobalComposer类实例化1000采用倍 App::make
  • 该事件composing:some_partial_view_to_display_i被处理 1000次。
  • 类中的compose函数GlobalComposer被调用了 1000 次。

But the partial view some_partial_view_to_display_ihas nothing to do with the variables composed by GlobalComposerbut heavily increases render time.

但是局部视图some_partial_view_to_display_i与由组成的变量无关,GlobalComposer但会大大增加渲染时间。

Best approach?

最好的方法?

Using View::sharealong a grouped middleware.

使用View::share分组中间件。

Route::group(['middleware' => 'WebMiddleware'], function(){
  // Web routes
});

Route::group(['prefix' => 'api'], function (){

});

class WebMiddleware {
  public function handle($request)
  {
    \View::share('user', auth()->user());
  }
}

Update

更新

If you are using something that is computed over the middleware pipeline you can simply listento the proper eventor put the view share middleware at the last bottom of the pipeline.

如果您使用的是通过中间件管道计算的东西,您可以简单地监听正确的事件或将视图共享中间件放在管道的最后一个底部。

回答by Samuel Kwame Antwi

The documentation is hear https://laravel.com/docs/5.4/views#view-composersbut i will break it down

文档是听到https://laravel.com/docs/5.4/views#view-composers但我会分解它

  1. Look for the directory app\Providersin the root directory of your application and create the file ComposerServiceProvider.phpand copy and past the text below into it and save it.

    <?php
        namespace App\Providers;
        use Illuminate\Support\Facades\View;
        use Illuminate\Support\ServiceProvider;
    
        class ComposerServiceProvider extends ServiceProvider
        {
            /**
            * Register bindings in the container.
            *
            * @return void
            */
        public function boot()
        {
            // Using class based composers...
            View::composer(
                'profile', 'App\Http\ViewComposers\ProfileComposer'
            );
    
            // Using Closure based composers...
            View::composer('dashboard', function ($view) {
                //
            });
        }
    
        /**
        * Register the service provider.
        *
        * @return void
        */
        public function register()
        {
            //
        }
    }
    
  2. From the root of your application open Config/app.phpand look for the Providers section in the file and copy and past this 'App\Providers\ComposerServiceProvider',to the array.

  1. 应用程序的根目录中查找目录app\Providers并创建文件ComposerServiceProvider.php并将下面的文本复制并粘贴到其中并保存。

    <?php
        namespace App\Providers;
        use Illuminate\Support\Facades\View;
        use Illuminate\Support\ServiceProvider;
    
        class ComposerServiceProvider extends ServiceProvider
        {
            /**
            * Register bindings in the container.
            *
            * @return void
            */
        public function boot()
        {
            // Using class based composers...
            View::composer(
                'profile', 'App\Http\ViewComposers\ProfileComposer'
            );
    
            // Using Closure based composers...
            View::composer('dashboard', function ($view) {
                //
            });
        }
    
        /**
        * Register the service provider.
        *
        * @return void
        */
        public function register()
        {
            //
        }
    }
    
  2. 从应用程序的根目录打开Config/app.php并查找文件中的 Providers 部分,然后将“App\Providers\ComposerServiceProvider”复制并粘贴到数组中。

By doing this, we have created the Composer Service Provider. When you run your application with the view Profile like so http://yourdomain/something/profile, the service provider ComposerServiceProvideris called and the class App\Http\ViewComposers\ProfileComposer is instantiated calling the method Composer due to the code below inside the boot method or function.

通过这样做,我们创建了 Composer 服务提供者。当你使用像http://yourdomain/something/profile这样的视图 Profile 运行你的应用程序时,服务提供者ComposerServiceProvider被调用,并且类 App\Http\ViewComposers\ProfileComposer 被实例化调用 Composer 方法,由于下面的代码启动方法或功能。

 // Using class based composers...
 View::composer(
   'profile', 'App\Http\ViewComposers\ProfileComposer'
 );
  1. If you refresh your application you will get an error because the class App\Http\ViewComposers\ProfileComposerdoes not exist yet. Now lets create it.
  1. 如果您刷新应用程序,您将收到错误消息,因为App\Http\ViewComposers\ProfileComposer类尚不存在。现在让我们创建它。

Go to the directory path app/Http

进入目录路径 app/Http

  • Create the directory called ViewComposers

  • Create the file ProfileComposer.php.

    class ProfileComposer
    {
        /**
        * The user repository implementation.
        *
        * @var UserRepository
        */
        protected $users;
    
        /**
        * Create a new profile composer.
        *
        * @param  UserRepository  $users
        * @return void
        */
        public function __construct(UserRepository $users)
        {
            // Dependencies automatically resolved by service container...
            $this->users = $users;
        }
    
        /**
        * Bind data to the view.
        *
        * @param  View  $view
        * @return void
        */
        public function compose(View $view)
        {
            $view->with('count', $this->users->count());
        }
    }
    
  • 创建名为ViewComposers的目录

  • 创建文件ProfileComposer.php

    class ProfileComposer
    {
        /**
        * The user repository implementation.
        *
        * @var UserRepository
        */
        protected $users;
    
        /**
        * Create a new profile composer.
        *
        * @param  UserRepository  $users
        * @return void
        */
        public function __construct(UserRepository $users)
        {
            // Dependencies automatically resolved by service container...
            $this->users = $users;
        }
    
        /**
        * Bind data to the view.
        *
        * @param  View  $view
        * @return void
        */
        public function compose(View $view)
        {
            $view->with('count', $this->users->count());
        }
    }
    

Now go to your view or in this case Profile.blade.php and add

现在转到您的视图或在这种情况下 Profile.blade.php 并添加

{{ $count }}

and that will show the count of users on the profile page.

这将在个人资料页面上显示用户数。

To show the count on all pages change

显示所有页面更改的计数

// Using class based composers...
View::composer(
    'profile', 'App\Http\ViewComposers\ProfileComposer'
);

To

// Using class based composers...
View::composer(
    '*', 'App\Http\ViewComposers\ProfileComposer'
);

回答by Santiago Mendoza Ramirez

In the documentation:

在文档中:

Typically, you would place calls to the share method within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them.

通常,您会在服务提供者的 boot 方法中调用 share 方法。您可以自由地将它们添加到 AppServiceProvider 或生成一个单独的服务提供者来容纳它们。

I'm agree with Marwelln, just put it in AppServiceProviderin the boot function:

我同意 Marwelln 的说法,只需将其放入AppServiceProviderboot 函数中即可:

public function boot() {
    View::share('youVarName', [1, 2, 3]);
}

I recommend use an specific name for the variable, to avoid confussions or mistakes with other no 'global' variables.

我建议为变量使用一个特定的名称,以避免与其他非“全局”变量混淆或错误。

回答by Panagiotis Koursaris

I think that the best way is with View Composers. If someone came here and want to find how can do it with View Composers way, read my answer => How to share a variable across all views?

我认为最好的方法是使用View Composers. 如果有人来到这里并想了解如何使用 View Composers 方式来实现,请阅读我的答案 =>如何在所有视图中共享变量?

回答by Mehran

Inside your config folder you can create a php file name it for example "variable.php" with content below:

在您的 config 文件夹中,您可以创建一个 php 文件名,例如“variable.php”,内容如下:

<?php

  return [
    'versionNumber' => '122231',
  ];

Now inside all the views you can use it like

现在在所有视图中,您可以像这样使用它

config('variable.versionNumber')

回答by Samuel Kwame Antwi

The documentation is here https://laravel.com/docs/5.4/views#view-composersbut i will break it down 1.Look for the directory Providers in your root directory and create the for ComposerServiceProvider.php with content

文档在这里https://laravel.com/docs/5.4/views#view-composers但我将其分解 1.Look 在您的根目录中的目录 Providers 并为 ComposerServiceProvider.php 创建内容

回答by Abdelhakim Ezzahraoui

1) In (app\Providers\AppServiceProvider.php)

1) 在 (app\Providers\AppServiceProvider.php)

// in boot function
       view()->composer('*', function ($view) {
            $data = User::messages();
            $view->with('var_messages',$data);
        });

2) in Your User Model

2)在您的用户模型中

  public static function messages(){ // this is just example
        $my_id = auth()->user()->id;
        $data= Message::whereTo($my_id)->whereIs_read('0')->get(); 
        return $data; // return is required
    }

3) in Your View

3) 在你看来

 {{ $var_messages }}