Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing data from middleware to view or alternative way to show specific data in every page

in my website i have a fairly complected category which i have to show in every view (in the client side) so i thought i put the code for creating category in a middleware and pass the result to views

so i've created my middleware but i cant figure out how can i pass its data to my view withouth having to do something in the controllers i've tried these methods in my middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CtegoryMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->merge(array("all_categories" => "abc"));
        $request['all_categories']= 'abc';
        return $next($request);
    }
}

route :

Route::group(['middleware' => ['category' ]], function () {
     Route::get('/', 'HomeController@index');
});

but in my view when i echo all_categories i get

Undefined variable: all_categories 

btw i've checked by echoing something , the middleware gets triggered on the request

like image 442
hretic Avatar asked Dec 10 '22 14:12

hretic


1 Answers

I think in your use case, using a globally available view variable should suffice.

<?php

namespace App\Http\Middleware;

use Closure;

class CtegoryMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->merge(array("all_categories" => "abc"));
        $request['all_categories']= 'abc';

        /**
         * This variable is available globally on all your views, and sub-views
         */
        view()->share('global_all_categories', 'abc');

        return $next($request);
    }
}

The variable is loaded once (if you do database query, the query will only execute once), and the variable is then stored in the View factory.

like image 84
JofryHS Avatar answered Dec 13 '22 02:12

JofryHS