'Header Footer Controller in Laravel

I am working on Laravel for the first time

i have to make a Front End Menu Dynamic in Header and Footer [ list of categories will come from database ]. which controller I have to use for this.? any common controller available in this framework to send data to header and footer.

When I receive the data in HomeController index Action its available for the home page only.

class HomeController {
public function index() 
    {
        $categories = Category::get();
        return view('home', compact('categories'));
    }
}

Thanks.



Solution 1:[1]

I assume you are using the Header and Footer in a master layout file. In this case you need to send all header/footer info every request. Which would be silly so instead use View Composers:

Define them in your appServiceProvider in the boot() method

view()->composer('home', function($view) {
   $view->with('categories', App\Category::all());
});

In my example i made 'home' the name of the view, since it is in your example. But i would make a master file called layout and include a header and footer partial. If you want categories inside your header you could make a view()->composer('layout.header') with only header data.

Solution 2:[2]

which controller I have to use for this.?

Any

any common controller available in this framework to send data to header and footer

No. You control what is returned from the Controller to be the response. You can design layouts and break them up into sections and have views that extend them. If you setup a layout that has the header and footer and your views extend from it, you can use a View Composer to pass data to that layout when it is rendered so you don't have to do this every time you need to return a view yourself.

Laravel Docs 5.5 - Front End - Blade

Laravel Docs 5.5 - Views - View Composers

Solution 3:[3]

In case of this u can use components

https://laravel.com/docs/8.x/blade#components

php artisan make:component Header

View/Component.Header.php

public function render()
{
    $category = [Waht you want];
    return view('views.header', ['category'=>$category]);
}

Then include Header.php to your blade like this views/front.blade.php

<html>
    <body>
        <x-header/> <!-- like this -->
        @yield('content')
        @include('footer')
    <body>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christophvh
Solution 2 lagbox
Solution 3 YoungHyeong Ryu