尝试查看 Laravel 7 中的不同内容时 Blade View 上的 ErrorException Undefined variable

ErrorException Undefined variable on Blade View when trying to View Different Contents in Laravel 7

我正在尝试使用

在我的 dashboard.blade.php 内部布局文件夹的 header 上执行 foreach 循环
@foreach ($moneytrades as $mt)
 <div class="col mr-2">
      <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Deposited</div>            
      <div class="h5 mb-0 font-weight-bold text-gray-800">Php {{ $mt->mt_deposit}}</div>
 </div>
@endforeach

我的web.php路线是

Route::get('/home', 'HomeController@index');

在我的 HomeController 上我有

public function index()
{
    $moneytrades = MoneyTrade::all();

    return view('layouts.dashboard', compact('moneytrades'));
}

这完全没问题。但是,我在循环下方有一个 @yield('content'),每当我单击按钮以路由到新页面时,我都会收到此错误消息

ErrorException Undefined variable: moneytrades (View: C:\xampp\htdocs\Laravel\fss\resources\views\layouts\dashboard.blade.php)

我该怎么做才能解决此问题,以便 layouts.dashboard 扩展的所有内容都可以与这些 foreach 循环一起使用?任何建议将不胜感激。非常感谢!

您可以使用视图组件,而不是使用部分组件(您正在为此做 @yield('content'))。

<div class="container">
        @component('content', ['moneytrades' => $moneytrades])
        @endcomponent
</div> 

然后在你的组件内容中访问,

   <div class="col-md-8">
         @foreach ($moneytrades as $mt)
            {{-- do whatever you want  --}}
         @endforeach
   </div>

编辑:在 blade 组件中查看组件可用于 Laravel >= 5.4。

您可以使用视图编辑器在多个视图之间共享日期。 例如,在您的 AppServiceProvider 的引导方法中,您可以添加:

View::composer(
    ['dashboard', 'other-view'],
    'App\Http\View\Composers\DashboardComposer'
);

并创建作曲家:例如“App\Http\View\Composers\DashboardComposer”

class DashboardComposer
{    
    public function compose(View $view)
    {
        $view->with('moneytrades', MoneyTrade::all());
    }
}

现在所有在 composer 注册的视图都可以访问 $moneytrades。 并且仅从操作 return 视图:

return view('layouts.dashboard'); // or any other registered view

查看文档:https://laravel.com/docs/7.x/views#view-composers