Controller Construct Session Changes in Laravel 5.3

Published on by

Controller Construct Session Changes in Laravel 5.3 image

Back in laravel 5.2, a developer was able to interact with the session directly in a controller constructor. However, this has changed in laravel 5.3.

The difference between how the 5.3 & 5.2 handle an incoming request is that in 5.2 the request goes through 3 pipelines:

  1. The global middleware pipeline
  2. The route middleware pipeline
  3. The controller middleware pipeline

By default the global middleware only contains a check for maintenance mode, the route middleware is what you assign to a route in your routes.php file, and by default, a web group is assigned to all web routes that contains several middlewares including the middleware that starts the session.

And then finally Laravel instantiates your controller to check for controller middleware, at this point, the request is all set up during the first and second pipelines, that’s why we were able to use sessions and auth in the controller constructor because the request is ready for it.

In 5.3 the request goes through only 2 Pipelines:

  1. The global middleware pipeline
  2. The route & controller middleware in 1 stack

Laravel collects all route specific middlewares first before running the request through the pipeline, and while collecting the controller middleware an instance of the controller is created, thus the constructor is called, however at this point the request isn’t ready yet, and that’s where the change in behaviour you notice in 5.3 exists.

The reason for this change is as Taylor described:

It’s very bad to use session or auth in your constructor as no request has happened yet and session and auth are INHERENTLY tied to an HTTP request. You should receive this request in an actual controller method which you can call multiple times with multiple different requests. By forcing your controller to resolve session or auth information in the constructor you are now forcing your entire controller to ignore the actual incoming request which can cause significant problems when testing, etc.

Using sessions in your constructor in 5.3

Maybe it was a bad practice to use the constructor of the controller to access session variables. However, it looks like a good chunk of laravel developers were using this approach and considered the constructor as an inline middleware where they can check if the user can access certain methods in this controller or not.

So the core team came up with a solution for this matter, it’s described in the upgrade guide as follow:

As an alternative, you may define a Closure based middleware directly in your controller’s constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:

Here’s the example from the docs:

<?php
 
namespace App\Http\Controllers;
 
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
 
class ProjectController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->projects = Auth::user()->projects;
 
return $next($request);
});
}
}
Mohamed Said photo

Web Developer and Laravel Core Contributor

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article