首页 > 解决方案 > Laravel如何在主模板文件中包含的所有视图中传递数据?

问题描述

我有一个主模板文件,它由不同的控制器和不同的视图调用。在页脚中显示类别列表,那么我如何从所有控制器的方法中传递数据而不在所有函数中编写代码并传递数据?

标签: laravellaravel-5

解决方案


在app/Providers/AppServiceProvider.php中获取类别 boot method

namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

use Illuminate\Support\Facades\Auth;
use DB;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
         View::share('key', 'value');
         Schema::defaultStringLength(191);

        $categories=DB::table('categories')->get();
        View::share('categories',$categories);  

    }

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

$categories现在您可以访问变量中所有视图和控制器中的类别

在您的页脚中:

@foreach($categories as $category)
   <p>{{$category->name}}</p>
@endforeach

推荐阅读