Github repository dedicated for my YT tutorial which shows how to use Sessions in Laravel

Overview

Sessions in Laravel

The following documentation is based on my Laravel Sessions for Beginners tutorial we’re going to cover the basics of sessions in Laravel.

• Author: Code With Dary
• Twitter: @codewithdary
• Instagram: @codewithdary

Usage

Setup your coding environment

git clone [email protected]:codewithdary/laravel8-tailwindcss2.git
cd laravel8-tailwindcss2
composer install
cp .env.example .env 
php artisan key:generate
php artisan cache:clear && php artisan config:clear 
php artisan serve 

Database Setup

We will be performing database tests which (obviously) needs to interact with the database. Make sure that your database credentials are up and running.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_sessions
DB_USERNAME=root
DB_PASSWORD=

Next up, we need to create the database which will be grabbed from the DB_DATABASE environment variable.

mysql;
create database laravel_sessions;
exit;

Finally, make sure that you migrate your migrations.

php artisan migrate

Session Configuration

When a user interacts with your web application, data needs to be stored temporary. In most cases, it will be done in a session.

A session allows you to store states between page requests. An example might be a product page. When you store a value from the product page inside a session, you can access that session in the shopping cart.

All your session settings and drivers are stored in the /config/session.php file. The first thing you’ll notice right here is that you have the option to change up your SESSION_DRIVER. This might seem odd, but you can actually choose between the following drivers:
• File (Default)
• Cookie
• Database
• Memcached
• Redit
• Amazon Web Service
• DynamoDB
• Basic array

Another interesting setting is the encrypt. You can choose whether you want to encrypt your session data or not. BY default, it’s always turned off. If you’re working with sentive data inside your sessions, you can set the value equal to true.

Creating our first session

I’ve created a new controller called PagesController and I’ve setup two methods and routes called index and about.

public function index()
{
    return view('index');
}

public function about()
{
    return view('about');
}

You can define a session through the Session Facade or the global session helper. I prefer to use the Session Facade so that’s what we’re going to use in this tutorial.

The two most common methods are get() and put(). The put() method allows you to save data, and it accepts two parameters. The first one will be the key, and the second parameter will be the value. The second parameter can also be an array with multiple values.

Session::put('name', 'John');

Whenever the index() method will be called, a new session with a key of name and a value of John will be created.

In order to retrieve data, we got to use the get() method. If we navigate to the index.blade.php file, we could use the Session façade in the same exact way to get a value. Be aware that you always need to provide a key of the session. You can attach a fallback value as well, which can be a string or a closure.

{{ Session::get('name') }}

{{ Session::get('name', 'Default name!') }}

A session should be accessible throughout the entire application. If we navigate to the /about page and print out the get() method with a key of name, you’ll see that our name will be printed out again.

Available methods on session instance

There are a couple important methods available that you can perform on your session Facade. We’ve already performed the two most basic ones, which is the get method to get data, and put to add values into our session.

Session::push($key, $value)

The next one will be the push method, which allows you to add a value to an array.

Session::put('name', ['John']);
Session:push('name', 'Michael');

Session::has($key)

The next method is a method I’ve used quite a lot in my tutorials, which is the has() method. The has method checks whether there’s a value set at the provided key.

if(Session::has('name')) {
    echo 'Name does exist';
}

Session::exists($key)

exists() will check whether there’s a value set at the provided key.

if(Session::exists('name')) {
    echo 'Name does exist';
}

Session::all()

The all() method returns an array of everything that’s in the session, including those values set by the framework.

Session::all();

Session::forget($key) & Session::flush()

forget() removes a previously set session value and the flush() method removes every session value, even those set by the framework.

Session::forget('name');
Session::flush();

Session::regenerate()

The last available method is the regenerate() method, which will regenerate the _token value from your session.

Session::regenerate();

How to store sessions in database

Whenever you want to combine session data with meta data, I recommend you to store sessions in the database because you can track whenever and how often a user has logged in. But you should also keep in mind that the numbers of record can grow tremendously inside your database, which can make your site slow as well.

Let’s pull in a frontend scaffolding to save a user_id inside a session.

composer require laravel/ui
php artisan ui vue –auth
npm install && npm run dev

We don’t need to generate the sessions migration ourselves because Artisan allows us to generate one.

php artisan session:table

This will create a new migration inside the /database/migrations folder with the name of {datetime}}_create_sessions_table.php.

Schema::create('sessions', function (Blueprint $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();
});

user_id is the user_id that is logged in. It’s optional, so you don’t need to be logged in to set the array. ip_address will be the ip address that you use when setting your session. On your localhost, this will most likely be 127.0.0.1. user_agent will be the software that present content for end users. payload is the portion of transmitted data. last_activity will be a datetime of when a user had his last activity.

You can only add your session into the database if you change up your SESSION_DRIVER. This can be done inside the /config/session.php file, but the best way is to define an env variable.

SESSION_DRIVER=database

Example

Change up the RegisterController so set a session when a user creates a new account

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);

    Session::push('user', [
        'id' => $data['id'],
        'name' => $data['name'],
        'email' => $data['email']
    ]);

    return $user;
}

If you then print out all values inside the PagesController:

dd(Session::all());

Refresh the /endpoint, where you find an name array with information of a user, and if you perform

SELECT * FROM sessions;

Inside MySQL, you’ll see a new session!

Credits due where credits due…

Thanks to Laravel for giving me the opportunity to make this tutorial on Sessions.

You might also like...
This repository is pre-configured, clean and empty skeleton for creating a new projects using Kraken Framework.

Kraken Application Skeleton Note: This repository contains pre-configured application skeleton for fast creation of new projects with Kraken Framework

This template repository is a boilerplate setup for a PHP application

PHP_Docker Repository Template What is this ? This template repository is a boilerplate setup for a PHP application. Its current version ships with PH

Laravel Vue SPA, Bulma themed. For demo login use `admin@laravel-enso.com` & `password` -
Laravel Vue SPA, Bulma themed. For demo login use `[email protected]` & `password` -

Laravel Enso Hit the ground running when building your new Laravel SPA project with boilerplate and extra functionality out of the box! click on the p

Laravel Vue SPA, Bulma themed. For demo login use `admin@laravel-enso.com` & `password` -
Laravel Vue SPA, Bulma themed. For demo login use `[email protected]` & `password` -

Laravel Enso Hit the ground running when building your new Laravel SPA project with boilerplate and extra functionality out of the box! click on the p

A Laravel 5.8 API Boilerplate to create a ready-to-use REST API in seconds.

Laravel API Boilerplate (JWT Edition) for Laravel 5.8 Laravel API Boilerplate is a "starter kit" you can use to build your first API in seconds. As yo

Automatically Create professional ready to use Laravel REST API for MySQL Database With Postman Docs and JWT Authentication

Laravel Simple Rest API Generator An API Boilerplate to create a ready-to-use REST API in seconds with Laravel 8.x Install with Composer $ curl -s

Api first backend boilerplate build with laravel 🎯 you can use as a template 😉

Laravel Backend Template i use this as a starting point for my backend projects , it saves time with basic auth functionalities and has code examples

Until 2018, Backpack v3 used this Base package to offer admin authentication and a blank admin panel using AdminLTE. Backpack v4 no longer uses this package, they're now built-in - use Backpack/CRUD instead.
Until 2018, Backpack v3 used this Base package to offer admin authentication and a blank admin panel using AdminLTE. Backpack v4 no longer uses this package, they're now built-in - use Backpack/CRUD instead.

Note: This package is only used by Backpack v3. Starting with Backpack v4, everything this package does is included in Backpack/CRUD - one package to

Symfony React Blank is a blank symfony and react project, use this template to start your app using Symfony as an backend api and React as a frontend library.

Symfony React Blank Symfony React Blank is a blank symfony and react project, use this template to start your app using Symfony as an backend api and

Owner
Code With Dary
I'm a developer & educator who creates online programming courses to help out anyone interested in learning web development.
Code With Dary
Laravel 8 boilerplate in docker-compose with Treafik and SSL setup and github workflow ready for CI/CD pipeline

Laravel8 boilerplate Laravel 8 boilerplate in docker-compose with Treafik and SSL setup with .github workflow ready To start the containers in prod en

Tej Dahal 5 Jul 9, 2022
LaraAdmin is a Open source Laravel Admin Panel / CMS which can be used as Admin Backend, Data Management Tool or CRM boilerplate for Laravel with features like Advanced CRUD Generation, Module Manager, Backups and many more.

LaraAdmin 1.0 LaraAdmin is a Open source CRM for quick-start Admin based applications with features like Advanced CRUD Generation, Schema Manager and

Dwij IT Solutions 1.5k Dec 29, 2022
Simplified Repository pattern implementation in Laravel

Laravository - Repository Pattern for Laravel Simplified Repository pattern implementation in Laravel. Requirement Laravel 8.x Installation Execute th

Benny Rahmat 14 Oct 1, 2021
An open source blog, made using Laravel, Inertia.js, and React.js. Also a learning repository.

Blog An open source Laravel-based blog. Still in progress, will be updated regularly as I wrote articles on my blog. Configurations Shared-hosting, an

Aghits Nidallah 8 Dec 6, 2022
A Laravel admin panel which is creating CRUD for your application automatically.

Adds a zero configuration Admin Panel to your Laravel Application Installation You can install the package via composer: composer require max-hutschen

42coders 10 Aug 24, 2022
A Laravel package which helps you automate creation of files.

Laravel file generator This is a Laravel package which helps you automate creation of files. High Res Link Benefits If you create a type of file frequ

Anirudh Sanjeev 63 Nov 29, 2022
A starter template from which to build Laravel + Vite apps

Stack The Laravel framework is fast, clean, and filled with best practices. In this stack, it will handle the backend as an API. The Laravel Vite pack

null 7 Nov 14, 2022
Template repository for new Blade Icons packages.

Blade Icons Template This is a template repository for new icon packages for Blade Icons.

Blade UI Kit 11 Nov 30, 2022
Template for repository helper, library - Basic, Simple and Lightweight

Template start helper, library Template for repository helper, library - Basic, Simple and Lightweight Use this Template First, you can Use this templ

Hung Nguyen 2 Jun 17, 2022
This is a repository for anyone wishing to contribute to HacktoberFest 2021

HacktoberFest 2021 Status IMPORTANT NOTICE : We have stopped accepting PRs for DSA Please Try to add more projects/apps/webapp instead of just DSA cod

Viral Vaghela 51 Nov 6, 2022