【问题标题】:Laravel How to pass data in all views included in main template file?Laravel如何在主模板文件中包含的所有视图中传递数据?
【发布时间】:2018-06-18 13:38:08
【问题描述】:

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

【问题讨论】:

标签: laravel laravel-5


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2015-06-24
  • 1970-01-01
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 2022-10-24
  • 2010-10-07
  • 2012-01-04
  • 2013-06-15
相关资源
最近更新 更多