Tutorialsplane

Laravel HTTP Session


Laravel HTTP Session – The Laravel HTTP Session is used to store information about the user requests. Laravel provides many driver to handle session data.


Laravel HTTP Session.

Let us understand how to use laravel Http Session.

Function:-

There are some followings function available in laravel Http Session.

1. Introduction.

It is used to store information about user requests. Laravel provides various drivers like file, cookie, apc, array, Memcached, Redis and database. by default file driver is used because it is lightweight.

Configuration

Session is configured in the file stored at config/session.php. laravel is configfure to use the file session driver which is work well for many application.

file– session are stored in storage/framework/sessions.
cookie– session are save in secure, encrypted cookies.
database– session are save in a relational database.
memcached/redis– session are save in one of these fast,cache based store.
array– session are store in a PHP array.

Driver Prerequisites

Database

Before using the database session driver. WE have to need to create table to contain the session items.

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

You can also use the session:table Artsian command to generate this table.

php artisan session:table

php artisan migrate

Redis

Before using Redis session in Laravel. We will need to install the predis/predis package via composer. You can configure your Redis connection in the database configuration file.

2. Using The Session.

Retrieving Data

There are two way to access session data first is global session helper and second one is request instance. Using request instance we can use the get() method, which will take one argument.

<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

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

The Global Session Helper

We can use global session php function to access and store data in the session. When the session helper is called with single argument it will return the value of that session key.

Route::get('home', function () {
    
    $value = session('key');

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

    session(['key' => 'value']);
});

Retrieving All Session Data

If you want to access all data in the session. You can use all method.

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

Determining If An Item Exists In The Session

The has method is used tp check value is present in session or not. If value is present then this function will return true. Otherwise it will return null.

if ($request->session()->has('users')) {
    return true;
}

If the value is null. Then you may use exists method.

if ($request->session()->exists('users')) {
    return true;
}

Storing Data

To store data in the session, you can use put method.

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

session(['key' => 'value']);

Pushing To Array Session Values

The push method can be used to push a new value on a session value that is an array.

$request->session()->push('user', 'Players');

Retrieving & Deleting An Item

The pull method is used to retrieve and delete item from the session in single statement.

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

Flash Data

Sometimes you want to store items in the session only for next request. You can use flash method. Flash data is primarily usefull for short-lived status message.

$request->session()->flash('status', 'Task was successful!');

Deleting Data

The forget method will remove a piece of data from the session. If you want to remove all data from the session you can use flush method.

$request->session()->forget('key');

$request->session()->flush();

Regenerating The Session ID

Laravel automaticallt regenerate session id when we use LoginController. If you need to manually regenerate session id, you can use regenerate method.

$request->session()->regenerate();

Full Example Using The Session:-

Create a controller page called SessionController by using Artsian command.

php artisan make:controller SessionController --plain

Controller Parts:-

Let’s look at a simple example.

<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class SessionController extends Controller
{
	 public function storeSessionData(Request $request)
	 {
      $request-?>session()->put('name','Sonu Kumar');
      echo "Data has been added to session";
     }
	 public function accessSessionData(Request $request)
	 {
      if($request->session()->has('name'))
         echo $request->session()->get('name');
      else
         echo 'No data in the session';
     }
  
   public function deleteSessionData(Request $request)
   {
      $request->session()->forget('name');
      echo "Data has been removed from session.";
   }
	
	
}

Route Path:-

Route::get('set','SessionController@storeSessionData');
Route::get('get','SessionController@accessSessionData');
Route::get('remove','SessionController@deleteSessionData');

Output of set Url is:-

Output of get Url is:-

Output of remove Url is:-

3. Adding Custom Session Drivers.

Implementing The Driver

The custom session driver should implement the SessionHandlerInterface. Just a few simple methods we need to implement.

Let’s look at a simple example.

<?php namespace App\Extensions;

class MongoHandler implements SessionHandlerInterface
{
    public function open($savePath, $sessionName) {}
    public function close() {}
    public function read($sessionId) {}
    public function write($sessionId, $data) {}
    public function destroy($sessionId) {}
    public function gc($lifetime) {}
}
</pre?>

The open method is used in file based session store system.
The close method is also used for disregarded.
The read method should return the string version of session data.
The write method should return write the given data string associate with session id.
The destroy method should remove the data with session id from storage.
The gc method should destroy all session data.

Registering The Driver

To add additional driver to laravel session backend, you can use the extend method on the session facade. You should call the extend method from the boot method of a service provider.

Let's look at a simple example.

<?php namespace App\Providers;
use App\Extensions\MongoSessionStore;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\ServiceProvider;

class SessionServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Session::extend('mongo', function ($app) 
       {
            return new MongoSessionStore;
        }
    }

    public function register()
    {
        //
    }
}
</pre?>

Once the session driver has been registered, you can use the mongo driver in your config/session.php configuration file.

Laravel Tutorial