0

In a web application I'm building with Laravel I'm trying to generate a menu based upon data in the database.

I'm able to create the middleware and I've added it to kernel.php so that it's executed upon every request. In the middware I can fetch the data from the model.

Now the next step I though I had to take was sending the data to the view. I've googled around for it, but I did not find any sample how to do this. Am I going the wrong way with middleware? or is there some way to do this?

3 Answers 3

2

You can use view composers to do this quite easily though it may not be the most efficient method. I've used it in similar circumstances before without issue.

Just drop it in your middleware after you've generated your menu.

view()->composer('*', function ($view) use ($menu) {
    $view->with('menu', $menu);
});
Sign up to request clarification or add additional context in comments.

2 Comments

great, that's exactly what I was looking for. I did not encounter View Composers before, I'll dive into that part of laravel so that I also know what I'm doing.
The reason I say it may not be the most efficient method is because this is going to load for every request. If there are going to be areas of your site where a menu is not needed, it would be better to create a new blade file just for your menu menu.blade.php and follow user diegoalmesp's directions except instead of *, use menu. That would ensure the code is only run whenever you are including the menu.
2

I've faced a similar problem not to long ago, I needed some categories displayed in the navbar, on every page. So I created a new Provider:

php artisan make:provider ComposerProvider

And this is the code inside:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function($view)
        {
            $view->with('categories', \App\Category::all());
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Then you can call the 'categories' variable in every page, or in the menu in my case. And that's it. Hope it helps!.

Comments

1

You may want something like this

 Route::group(['middleware' => 'yourMiddleware'], function () {

        Route::get('/route', function () {
            $menu = Menu::all();
            return view('viewfolder.index', compact($menu));
        });

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.