Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amk's avatar
Level 4

I am calling query in every single function for navbar

I am calling query in every single function for navbar

  public function home()
  {
        $navbar = Course::all();
        $class = Class_::where('is_delete',0)->get();
        return view('frontend.home',compact('class','navbar'));
  }


    public function cart_list()
    {
     $navbar = Course::all();
        return view('frontend.cart_list',compact('navbar'));
    }

    public function class_list($course_)
    {
        $navbar = Course::all();
        $class = Class_::all();
        return view('frontend.class_list',compact('class','navbar'));
    }


    public function classdetail($id)
    {
        $navbar = Course::all();
        $class = Class_::findOrFail($id);
        return view('frontend.class_detail',compact('class','navbar'));
    }

my file structure like this..

header.blade.php
navbar.blade.php
master.blade.php
footer.blade.php

I don't want to call navbar query in every function.. Pls suggest me..

0 likes
4 replies
tykus's avatar

View Composers can solve this issue if there is a common view (or view path) which uses that variable

1 like
Cronix's avatar
Cronix
Best Answer
Level 67

Several ways, but the simplest is

/app/Providers/AppServiceProvider

public function boot()
{
    // when navbar view is called
    View::composer('navbar', function ($view) {
        // pass it a variable called $navbar containing all courses
        $view->with('navbar', Course::all());
    });
}
public function home()
{
    //$navbar = Course::all();
    $class = Class_::where('is_delete',0)->get();
    //return view('frontend.home',compact('class','navbar'));
    return view('frontend.home',compact('class'));
  }

https://laravel.com/docs/5.7/views#view-composers

1 like
tykus's avatar

@amk I think the docs explain the options you have available to you very well. You have the option of Closure- and Class-based View Composers and either will work well for you.

https://laravel.com/docs/master/views#view-composers

In your case, I would consider the following if the navbar is rendered with every page in your application:

View::share('navbar', Course::all(()

Otherwise if you need to be selective, I would prefer with a Closure approach. Create a dedicated ServiceProvider to register the view composer(s) using the the following command to create that class for you in app/Providers/ViewComposerServiceProvider.

$ php artisan make:provider ViewComposerServiceProvider

There you can fetch the data an pass it to the specified view template whenever it is rendered.

public function boot()
{
        View::composer('navbar', function ($view) {
        $view->with('navbar', \App\Course::all());
    });
}

Aside, you could consider caching that query result if it was being used everywhere.

1 like

Please or to participate in this conversation.