Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

it is quite difficult to explain my question. I hope you will be able understand it.

For my project I have a master layout which contains the header and yield of content.

master.blade.php

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

now on main public route I am raturning a method.

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]);
    }
}

Now my query is, 'main-categories-page' is yielding in content section of master. but I want the same data of Mainadtype in header also. So I want to return view of header on same function. Please help if u understand it.

what I am trying now is,

 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]);
    }

But I know we cant return in this way. Thanks in advance.

like image 211
Omi kabira Avatar asked Jan 20 '26 01:01

Omi kabira


1 Answers

You can access the variable in the header as well. Just have a check to see if the variable exists so that you don't get errors when you load other views.

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

This way your data will be available when you are on index page.

If you want the data to be available in all views, you can use laravel view composer. From official docs:

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

Hope it helps.

like image 186
Sayantan Das Avatar answered Jan 22 '26 18:01

Sayantan Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!