Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

afoysal's avatar

Session::get('') inside boot() of AppServiceProvider

How can I get access of Session::get('') inside boot() function of AppServiceProvider class ?

My code is like below

<?php

namespace App\Providers;

use App\Models\Cashier\Subscription;
use App\Models\Cashier\SubscriptionItem;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Laravel\Cashier\Cashier;

use Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;

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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
        Cashier::useSubscriptionModel(Subscription::class);
        Cashier::useSubscriptionItemModel(SubscriptionItem::class);

        try {
            $response = Http::withToken(Session::get('SesTok'))->get('someURL'); 
            
            $number = count($response->json()['logs']);

            View::share(['number'=>$number]);
        } catch (Exception $exception) {
            //some code
        }
    }
}

0 likes
6 replies
martinbean's avatar

@afoysal You don’t, because you shouldn’t be trying to access session variables in a service provider at all.

1 like
afoysal's avatar

Thanks @martinbean . What will be the better approach in this regard ? I am trying to create a Global Variable which will be available in all Views.

afoysal's avatar

Thanks @martinbean . Can I use Session::get() inside View::composer() like below ?

public function boot()
{
    View::composer('*', function ($view) {
        // Can I use Session::get() here ?
        $view->with('channels', AppChannel::all());
    });
}
martinbean's avatar

@afoysal You should be able to, yes. But what is it from the session that you’re needing to inject into every view?

Snapey's avatar

don't use * in your view composer unless you absolutely know you need it. The database will be queried for every view. This includes every blade file including includes and blade components.

Please or to participate in this conversation.