2

Is there a way to pass a variable to the view with middleware?
I was able to do this using a session, but this didn't resolve my problem, so I'm asking for this.

hf923hf982h3f
  • 21
  • 1
  • 2

4 Answers4

4

Middleware is used to modify the request.

If you have some dynamical data that you use for each view then its best to use a service provider and not middleware.

For example, you may have on each page some meta data and each view includes a header.blade.php which may look like this:

<head> <meta name="{{$meta_key}}" content="{{$meta_desc}}"> </head>

Then you could create a service provider

 public function boot()
 {
    view()->composer('view', function () {
        $slug = request()->path();

        $meta = \MetaTags::where('slug' ,'=',$slug)->first();

        $view->with('metatag', $meta->tag);
    });
 }

You may also check this tutorial from laracast

Adam
  • 25,960
  • 22
  • 158
  • 247
  • I'd like to add dynamic data which need to request database and memcached to all views, should I use middleware or service provider? – shintaroid Mar 04 '20 at 08:16
  • @shintaroid service provider. – Adam Mar 04 '20 at 09:52
  • Thanks bro! https://stackoverflow.com/questions/28608527/how-to-pass-data-to-all-views-in-laravel-5 by the way, in the left question there are answers suggest using middleware (if I'm not misunderstanding the question), do you think middleware is also a solution? – shintaroid Mar 04 '20 at 10:38
1

Using the following code, you can easily access the data in the view:

view()->share('my_variable', $variable);

Now you can use {{$my_variable}} in your views.

0

You can merge the variable into the request, read it from the request on the controller, and then pass that on to the view.

For example, in the middleware:

public function handle($request, Closure $next)
{
    $foo = 'bar';
    $request->merge(compact('foo'));

    return $next($request);
}

On the controller:

public function create(Request $request)
{
    $foo = $request->foo;
    return view('my.view', compact('foo'));
}

Then on the view, you can reference it as, e.g. {{ $foo }}.

wunch
  • 1,092
  • 9
  • 12
0

Replace 'view' in composer by path where to you want send data

i.e. if you want to send to header.blade.php which is in partials folder,then replace 'view' as 'partials.header' .

After referring @adam answer and Laracasts episode 25 following code work for me:

\app\Providers\AppServiceProvider.php

Add following codes in boot() function :-

 view()->composer('partials.header', function ($view) {
            //

            $view->with('your_key', 'your_value');
        });

Now your data is available at project_name\resources\views\partials\header.blade.php as

{{$your_key}}

or

<?php echo $your_key; ?>
Satish
  • 696
  • 1
  • 11
  • 22