hretic hretic - 1 month ago 9
PHP Question

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

Answer

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.

Comments