如何 return 在 laravel 中的一个函数中对同一路线进行多个视图

How to return multiple views in one function in laravel for same route

很难解释我的问题。我希望你能理解它。

对于我的项目,我有一个主布局,其中包含 header 和内容产出。

master.blade.php

 @include('partials.header')
    <div class="container-fluid main-con">
        @yield('content')
        @include('partials.footer')
    </div>  

现在在主要 public 路线上,我正在修改一个方法。

Web.php

Route::get('/', [
    'uses' => 'ProductContoller@getIndex',
    'as' => 'product.mainCats'
]);

ProductContoller.php

class ProductContoller extends Controller
{

    public function getIndex(){
        $ad_cats = Mainaddtype::orderBy('title')->get();
        return view( 'shop.main-categories-page', ['mediacats' => $ad_cats]);
    }
}

现在我的查询是,'main-categories-page' 在 master 的内容部分产生。但我也想要 header 中 Mainadtype 的相同数据。所以我想 return 查看 header 相同的功能。明白的请帮忙

我现在正在尝试的是,

 public function getIndex(){
        $ad_cats = Mainaddtype::orderBy('title')->get();
        return view( 'shop.main-categories-page', ['mediacats' => $ad_cats]);
        return view( 'partials.header', ['mediacats' => $ad_cats]);
    }

但我知道我们不能这样return。 提前致谢。

函数在获得第一个 return 语句时终止,并且两个视图不能 return 在 laravel 中编辑,您唯一可以做的就是包含视图在布局模板中。在模板中添加类别视图的示例。

@if(showStore)
@include('store.category')
@endif

您也可以访问 header 中的变量。只需检查变量是否存在,这样当您加载其他视图时就不会出错。

@if(!empty($mediacats))
   // do awesome stuffs with $mediacats
@endif

这样,当您位于索引页时,您的数据将可用。

如果您希望数据在所有视图中都可用,可以使用laravel view composer。来自官方文档:

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location

希望对您有所帮助。