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 Ajax laravel Image Upload

Ajax laravel Image Upload with form with example

June 6, 2022November 6, 2023

In this tutorial i will show you to use Ajax laravel image Upload with form in laravel . This can be implement easily using the laravel file and storage providers. in our recent articles of How to Upload image with preview in Laravel 8 with example ? i explained to…

Read More
Php How to Get Current Url in Blade File Laravel

How to Get Current Url in Blade File Laravel ?

October 27, 2022March 16, 2024

Sometimes in our application we want to Get Current Url in Blade file Laravel because we want to add specific conditions to show the data on behalf of current url. It can be complete url, route name and query params too so that we can fetch the data accordingly and…

Read More
Php install laravel composer

How to install laravel 8 ?

September 20, 2021May 6, 2022

Laravel is most popular framework of PHP. It provides lots of in-build tools and library to build the web application. Laravel is used to to create robust custom web applications with ease of amazing developer experience. Laravel is easily customizable and provides tools like ORM, Validation libraries, Queue, Mail, Routing,…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version