How Can I Create Sessions In Laravel With Examples

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

session variables solve this problem by storing user information to be used across multiple pages. By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application.sessions provide a way to store information about the user across multiple requests. Laravel ships with a variety of session backends that are accessed through an expressive, unified API. Support for popular backends such as Memcached, Redis, and databases is included out of the box.

How Can I Create Sessions In Laravel With Examples

The session configuration file is stored at config/session.php. Be sure to review the options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for many applications.

The session driver configuration option defines where session data will be stored for each request. Laravel ships with several great drivers out of the box:
 

  • file - sessions are stored in storage/framework/sessions.
  • cookie - sessions are stored in secure, encrypted cookies.
  • database - sessions are stored in a relational database.
  • memcached / redis - sessions are stored in one of these fast, cache based stores.
  • array - sessions are stored in a PHP array and will not be persisted.

Example(1)

1.Create route in routes\web.php as below created.
Route::get('form', 'demoController@form');

2.Create demoController using below command 
php artisan make:controller demoController

3.Open app\Http\demoController.php 
 
<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{  
    public function form(){

       return view('form');
    }
}

4.Now Create form.blade.php in resource\routes.php  and open form.blade.php file to implement below code in it.
<!DOCTYPE html>
<html>
<head>
    <title>Session In Laravel</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>Session In Laravel</h1>
    </div>
    <div class="form-group col-sm-2"></div>
    <div class="form-group col-sm-8">
        <div class="well">
            <form method="post" action="{{url('formstore')}}">
                @csrf
                <div class="form-group col-sm-12">
                    <label>UserName</label>
                    <input  class="form-control" type="text" name="username" value="">
                </div>
                <div class="form-group col-sm-12">
                    <label>Password</label>
                    <input  class="form-control" type="text" name="password" value="">
                </div>
                <div class="form-group text-center">
                    <input  class="btn btn-primary" type="submit" >
                </div>
            </form>
            <div class="form-group col-sm-2"></div>
        </div>
    </div>
    <br>
</div>
</body>
</html>

5.Now again open app\Http\demController.php to create formstore method in it.so that request data can store.
<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){
       return $request->all();
    }
   
}

To see output pass below url
http://localhost/laraveldemoproject/public/formstore


Storing the data in a session

To store the user name in a session, we use the put() method of session as shown below:

$request->session()->put('user', $request->input('username'));

To retrieve the session, we use the get() method of session as shown below:

echo $request->session()->get('user');

<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){
        $request->session()->put('user', $request->input('username'));
        echo $request->session()->get('user');
    }

}


To see output pass below url 

http://localhost/laraveldemoproject/public/formstore


Global Session Helper
 

We can also use the global session function that stores and retrieves the value in a session. When the session function is passed with a single parameter, then it returns the value of the key. If the session is passed with an array of key/value pairs, then the values are stored in the session.

// Retrieve a data from the session key.

$data=session('key');

//Providing a default value to the session key.

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

// Storing the value in the session key.

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

 

For Example:

demoController.php

<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){
        session(['user'=>$request->input('username')]);
        $data=session('user');
        echo $data;
    }

}


Retrieving all session data
 

If we want to retrieve all the session data, then we can use the all() method as shown below:

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

For Example:

demoController.php

<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){
        session(['user1'=>'test1']);
        session(['user2'=>'test2']);
        return $request->session()->all();
    }

}


Deleting the session

Now, we will see how to delete the data from the session. We can delete the session by using the forget() method.

For Example:

demoController.php

<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){
        session(['user1'=>'test1']);
        session(['user2'=>'test2']);
        $request->session()->forget('user1');
        return $request->session()->all();
    }

}


 

To remove all the data from the session, then we will use the flush() method.

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

For Example:

demoController.php

<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){
        session(['user1'=>'test1']);
        session(['user2'=>'test2']);
        $request->session()->flush();
        return $request->session()->all();
    }

}


 

Flashing data

Flash data is useful when we want to store the data in the session for the current request as the flashed data is removed in the next request.

For Example:

demoController.php

<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){
        session()->flash('post', 'post has been updated');
        return $request->session()->get('post');
    }

}


When we remove the flash() function from the code, then the code would look like:

<?php

namespace App\Http\Controllers;

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

class demoController extends Controller
{
    public function form(){

       return view('form');
    }
    public function formstore(Request $request){
        return $request->session()->get('post');
    }

}


When we refresh the page twice, then on the second refresh, the session data will be deleted.
 

Related Post