Laravel 8 Tutorial - HTTP Session

In this video, we are going to learn about HTTP Session in Laravel. All HTTP-driven applications are stateless, meaning they do not retain any information about the user between requests.

Sessions provide a way to store information about the user across multiple requests. Laravel provides various drivers, such as file, cookie, array, Redis, and database, to handle session data.

By default, the file driver is used because it is lightweight. Sessions can be configured using their configuration file.

So, let's see the session configuration file. Go to the project and open the config folder. Inside the config directory, you can see the session.php file. Just open this.

Here, you can see session-related configuration. Let's see how we can use sessions in Laravel 8. For that, let's create a controller.

So, switch to the command prompt and run the following command:


php artisan make:controller SessionController

Now, let's open the SessionController file and create a function:


public function getSessionData(Request $request)
{
if($request->session()->has('name'))
{
echo $request->session()->get('name');
}
else
{
echo 'No data in the session';
}
}

Now, create another method for storing session data:


public function storeSessionData(Request $request) {
$request->session()->put(name','Jenifer');
echo "Data has been added to session";
}

Now, create another method for deleting session data:


public function deleteSessionData(Request $request) {
$request->session()->forget('my_name');
echo "Data has been removed from session.";
}

Ok, now create the routes for these methods. So, just go to the web.php and create routes:


Route::get('session/get',[SessionController::class,'accessSessionData');
Route::get('session/set',[SessionController::class,'storeSessionData');
Route::get('session/remove',[SessionController::class,'deleteSessionData');

Now, let's check. So, go to the browser and set the session. Go to the URL:

http://localhost:8000/session/set

Ok, now you can see the message. Session created! Now, get the session data. Go to the URL:

http://localhost:8000/session/get

And you can see the stored session data, which is "jenifer". And finally, just remove the session data. Type:

http://localhost:8000/session/remove

So, in this way, you can use HTTP Session in Laravel 8.