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

MiroslavDonic's avatar

Can I use session in AppServiceProvider?

I can sue session in View composer my code looks like

public function boot()
    {
        View::composer('*', function($view)
        {
            $cart_total = ($session->get('total')) ? $session->get('total') : 0;
            $view->with('category', Category::all());
            $view->with('cart_total',$cart_total);
        });
    }

but this produce error Undefined variable: session

0 likes
1 reply
RomainLanz's avatar
Level 14

You should use the helper session().

/**
 * Get / set the specified session value.
 *
 * If an array is passed as the key, we will assume you want to set an array of values.
 *
 * @param  array|string  $key
 * @param  mixed  $default
 * @return mixed
 */
function session($key = null, $default = null)
{
    if (is_null($key)) {
        return app('session');
    }

    if (is_array($key)) {
        return app('session')->put($key);
    }

    return app('session')->get($key, $default);
}

Or you can also use the container app('session')->get('...')

1 like

Please or to participate in this conversation.