Qazi
Qazi

Reputation: 5135

Laravel: How to access session value in AppServiceProvider?

Is there any way available to access Session values in AppServiceProvider? I would like to share session value globally in all views.

Upvotes: 17

Views: 14430

Answers (3)

Solo.dmitry
Solo.dmitry

Reputation: 770

Add new web middleware ShareDataForView

in \app\Http\Kernel.php:

protected $middlewareGroups = [
    'web' => [
        // ...
        \Illuminate\Session\Middleware\StartSession::class,
        // I will always ShareDataForView after StartSession
        \App\Http\Middleware\ShareDataForView::class,
...

and write your code in method "handle" of app\Http\Middleware\ShareDataForView.php, for example:

<?php

namespace App\Http\Middleware;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Closure;
use Log, Exception, View;

class ShareDataForView
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $user  = Auth::user();
        $bank = NULL;
        if ( $user ){
            $bank = $user->bank;
        }
        View::share('user', $user);
        session()->put(['bank' => $bank]);

        return $next($request);
    }
}

Upvotes: 4

Moppo
Moppo

Reputation: 19285

You can't read session directly from a service provider: in Laravel the session is handled by StartSession middleware that executes after all the service providers boot phase

If you want to share a session variable with all view, you can use a view composer from your service provider:

public function boot()
{
    view()->composer('*', function ($view) 
    {
        $view->with('your_var', \Session::get('var') );    
    });  
}

The callback passed as the second argument to the composer will be called when the view will be rendered, so the StartSession will be already executed at that point

Upvotes: 36

kalatabe
kalatabe

Reputation: 2989

The following works for me on Laravel 5.2, is it causing errors on your app?

AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    \Session::put('lang', 'en_US');
    view()->share('lang', \Session::get('lang', 'de_DE'));
}

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    //
}
}

home.blade.php

<h1>{{$lang}}</h1>

Shows "en_US" in the browser.

Upvotes: 0

Related Questions