DEV Community

Robert Look
Robert Look

Posted on

How To Set Session In Laravel?

n this tutorial, we will learn how to set session in laravel.

Sessions are used to store user information requests. Laravel provides various drivers like file, cookie, array, and database, etc. to handle session data. By default, the file driver is used because it is lightweight. Session can be configured in the project stored at config/session.php.

Accessing Session Data
we need an instance of session which can be accessed via HTTP request. After getting the instance, we can use the get() method, which will be take one argument, “key”, to get the session data.

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

Storing Session Data
Data can be stored in the session using the put() method. The put() method will be take two arguments, the “key” and the “value”.
$request->session()->put('key', 'value');

app/Http/Controllers/SessionController.php
<?php

namespace App\Http\Controllers;

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

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

Read More: https://www.phpcodingstuff.com/blog/how-to-set-session-in-laravel.html

Top comments (0)