按照指南,我有
1)创建服务提供商
class ViewComposerServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { view()->composer('template',function ($view) { $view->with('series_list',Series::all()); }); } /** * Register the application services. * * @return void */ public function register() { // } }
2)注册提供商
App\Providers\ViewComposerServiceProvider::class,
3)并在模板上回显变量
{!! var_dump($series_list) !!}
问题是 :
Route::get('/','HomeController@index'); Route::get('product/view/{id}','ProductController@view'); Route::get('product/detail/{id}','ProductController@detail'); Route::get('/page/contact','PageController@contact');
PageController和HomeController可以显示$series_list,但ProductController将返回错误:
Undefined variable: series_list in the template
这是ProductController:
class ProductController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { //$this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function view($id = 1) { return view('product/list'); } public function detail($id = 1) { return view('product/detail'); } }
非常感谢您的帮助.
另一种方式,有点短
class AppServiceProvider extends ServiceProvider { // other methods public function boot() { $series = Series::all(); view()->share('series_list',$series); } // other methods }