skip to Main Content

I want to use data in multiple views throughout my project, but I don’t have an example of what I want to share. I have read about the View::composer method, but I am not sure if this is the right approach. Can anyone provide an example of how to use this method or suggest an alternative method for sharing data across all views in Laravel?

I have find this syntax :

 public function boot()
    {
        // Using class based composers...
        View::composer('profile', ProfileComposer::class);
 
        // Using closure based composers...
        View::composer('dashboard', function ($view) {
            //
        });
    }

Thank you !

2

Answers


  1. The documentation has a section about this: https://laravel.com/docs/9.x/views#sharing-data-with-all-views

    public function boot()
    {
        View::share('global_value', 'yep this is a global value');
    }
    
    Login or Signup to reply.
  2. In your /app/Providers/AppServiceProvider file in boot method you can add the varibale and then use it any blade View:

    public function boot()
    {
        $media_url="https://www.google.com/";
        $subject = Subject::get();
    
        view()->share('media_url', $media_url);
        view()->share('subject', $subject);
    }
    

    Now you can use $media_url, $subject on any of your blade directly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search