laravel 与所有视图共享数据

在 app\Providers\AppServiceProvider.php的 boot 选项添加:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 与所有视图都输出这个变量
        View::share([
            'code' => '200',
            'msg' => '成功',
            'data' => [
                'name' => 'linfeng',
                'age' => '24',
            ],
        ]);
    }

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

 

然后你就可以在任意视图输出里面的变量了。比如:

{{$code}}  - {{$msg}} - {{$data['name']}} - {{$data['age']}}

 

posted @ 2018-12-28 14:36  小寒1206  阅读(343)  评论(0编辑  收藏  举报