尝试使用服务提供商在@extends('layouts.app')但不工作的所有视图页面中设置变量,首先我会显示以下代码。
AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Auth;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Using class based composers...
view()->composer('layouts.app', function($view){
$view->with('current_user', Auth::user());
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
当我访问调用{{$ current_user}}的网页时,会显示以下错误
ErrorException in 5a5612347179ad88a6d4ebacc5d911a184c1b4ed.php line 14:
Undefined variable: current_user (View: C:\xampp\htdocs\soyegg\resources\views\shops\edit\showroom.blade.php)
在网站上解决了几个问题并检查了以下内容但仍然失败了: 1. AppServiceProvider在config.app中(Laravel 5.2默认) 2. php artisan clear-compiled 3. php artisan优化 4.检查是否有compile.php并尝试手动清除它,但既没有存储/框架也没有供应商。
请帮忙!
答案 0 :(得分:0)
我认为您的ServiceProvider
工作正常,您只需要更改将数据传递到视图的方式。我自己进行了测试,我可以确认将数据传递到稍后将包含在@extends()
中的视图中,但这样做无法正常工作。相反,您可以使用其他方法:
view()->share('current_user', Auth::user());
或使用通配符:
view()->composer('*', function ($view) {
$view->with('current_user', Auth::user());
});
// wildcard with prefix
view()->composer('prefix.*', function ($view) {
$view->with('current_user', Auth::user());
});