问题:
使用laravel5.8,前台所有页面需要共用标签数据
解决方法:
1. 新建ComposerServiceProvider
php artisan make:provider ComposerServiceProvider
2. 编辑ComposerServiceProvider中都boot方法,添加
view()->composer('home.*','App\Http\ViewComposers\BaseInfoComposer');
说明:所有前台模板在home文件夹下,所以home.*
3. config/app.php中注册ComposerServiceProvider providers中添加App\Providers\ComposerServiceProvider::class 4. app/Http目录下新建ViewComposers文件夹,并在该文件夹下新建BaseInfoComoser.php文件夹 5. 编辑BaseInfoComposer.phpnamespace App\Http\ViewComposers; use Illuminate\Http\Request; use Illuminate\View\View; use App\Models\Tag; use App\Models\Link; class BaseInfoComposer { public function compose(View $view) { $tags = Tag::where('id','>',0)->orderBy('id','DESC')->get()->toArray(); $links = Link::where('id','>',0)->orderBy('id','DESC')->get()->toArray(); $view->with([ 'tags' => $tags, 'links' => $links, ]); } }
至此完工,前台所有模板以及模板调用都组件都可以使用$tags和$links变量