Question about View Sharing

Posted 2 months ago by pickab00

I wanted to share a variable with all my views so I went on ahead and used my Service provider boot() method to share my variable with all my views using View::share. But the problem was, I had to take the auth user information and as the service provider is loaded before, it returns null.

So I went on ahead and tried this.

public function __construct()
{
    $this->middleware(function ($request, $next) {

        $auth = Auth::user();

        $auth_menu = User::with('menus')->findOrFail($auth->id);

        view()->share('auth_menu', $auth_menu);

        return $next($request);
    });

}

This is inside of my Controller. As in the main controller which extends to base controller and I wanted to know if this method is

A. Safe? B. Good practice?

Now the second thing I did was to make a middleware ShareMenuVariable:

public function handle($request, Closure $next)
{

    $auth = Auth::user();

    $auth_menu = User::with('menus')->findOrFail($auth->id);

    view()->share('auth_menu', $auth_menu);

    return $next($request);
}

And in my kernel I called it in my web group \App\Http\Middleware\ShareMenuVariable::class, so it will always run in web routes.

So which method is better/safe/best practice and which method should I be using and why?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.