Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel session

How to set and get session in Laravel 8?

Aman Jain, November 8, 2021November 17, 2021

Laravel has its own class to manage the session using the file system, redis, array, cookie and database. Session are used to keep the information about the user across the multiple request. As we know PHP is a server side language and all information lost after the response, so keep the information of user we need sessions. Laravel has drivers to use the session with database, file system, reds etc.

Configuration of session in Laravel

All configuration of session in Laravel stored in config/session.php file where we can define session driver, secure, path, database configuration, session time etc.


<?php

use Illuminate\Support\Str;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "dynamodb", "array"
    |
    */

    'driver' => env('SESSION_DRIVER', 'file'),
   ....... 

];

If you want to configure session using the database then you will need to create table for session in database. Laravel provides artisan command to generate the table or you can create the same table as below

Schema::create('sessions', function ($table) {
    $table->string('id')->primary();
    $table->foreignId('user_id')->nullable()->index();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity')->index();
});

Commands to migrate

php artisan session:table

php artisan migrate

Initializing session in Laravel

Session in laravel initialized by web middleware in kernel.php and the name of class is StartSession

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    
    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            ...
            \Illuminate\Session\Middleware\StartSession::class,
           ..
        ],
 
}

Set session variable in laravel

There is two way to set and get the data in session.

  1. Set/Get session globally using helper function session()
  2. Set/Get session using $request service in controller

Set session using $request set method, set method accepts two arguments first is key and secound is default value

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserController extends Controller
{
    
    public function show(Request $request, $id)
    {
        $value = $request->session()->set('key');
    }
}

Or set session using global helper

    $value = session('key', 'default');

Get session value in Laravel

Same as set session we can use $request or session() function to get the session data.

    $value = session('key');

or using $request we can put method, put method accepts 2 arguments one is key and secound is value

    $value = $request->session()->put('key','value');

We can also set multiple value using session() function

    $value = session(['key'=>'value','key2'=>'value2']);

Get all session data

To get all stored value in session

$Alldata = $request->session()->all();

Delete Session data

If we would like to delete the session key then we can use forget method with an argument key and if we want to delete all session items from user session then we can use flush() method

// forget single item
$request->session()->forget('key');

// Forget multiple keys...
$request->session()->forget(['key', 'key2']);

// Forget all items from session
$request->session()->flush();

Related

Php Laravel laravelphpsession

Post navigation

Previous post
Next post

Related Posts

Php How to Use Broadcast to Send Web Socket Event in Laravel

How to Use Broadcast to Send Web Socket Event in Laravel ?

June 23, 2022June 26, 2022

Broadcasting is used to send real time message to client. In this article we will learn to use broadcast to send web socket event in laravel. Web sockets are used to communicate with client from server for real time communication. Broadcasting very useful to send update to client when any…

Read More

Laravel 10 – Error During installation laravel/framework[v10.0.0] require composer-runtime-api ^2.2 – Solved

March 8, 2023March 16, 2024

Today i was installing laravel 10 with php version 8.2 and i encountered an issue laravel/framework[v10.0.0, …, v10.3.2] require composer-runtime-api ^2.2 -> found composer-runtime-api[2.1.0] but it does not match the constraint. This issue occurred due to old composer. So we can quickly fix this by running below command May be…

Read More
Php Create Custom Directives in Laravel

How to create custom directive in Laravel 8 ?

November 11, 2021November 5, 2023

Laravel blade is powerful template engine which makes short tags directive and easy to reuse templates. Most of the templates restrict to use other language but blade gives more flexibility and we can use PHP as well in template. Directives start with prefix @ and accepts parameter. In this article…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version