March 13, 2024 • For devs

Laravel 11 - whats new?

Laravel 11 - whats new?

We're Streply, a tool that tracks errors and manages logs quickly. It's easy to set up and compatible with many popular frameworks. Made by developers, for developers! If you need to keep an eye on errors and follow logs in your app, create free account.

 

Welcome to our comprehensive guide on what's new in Laravel 11. Laravel, a popular PHP framework, has just announced its latest version, Laravel 11, which is packed with exciting new features and improvements. This article will walk you through these updates, helping both beginners and experienced Laravel developers get up to speed with the latest advancements in the framework.

No Support For PHP 8.1 in Laravel 11

Laravel version 11 no longer supports PHP 8.1. This is because, by the time Laravel 11 comes out, PHP 8.2 and 8.3 will be stable and better options.

Few people still want PHP 8.1 when there are improved versions available. But you don't have to switch right away; you could test the new versions first.

You might want to update your apps gradually. But choosing the latest version would be a good choice.

 

Simpler Application Framework

Laravel 11 brought changes to make the structure of a Laravel application clearer and simpler. The aim was to provide a cleaner and more effective starting point for your projects. And it certainly did that.

  • In the friendly AuthServiceProvider, the framework works its magic to discover and sweep away the $policies for you.
  • No need to worry about SendEmailVerificationNotification hanging around in the EventServiceProvider. This is because the base EventServiceProvider has got it covered. Plus, brace yourself for this - Laravel now has auto-event discovery turned on by default.
  • Say goodbye to the BroadcastServiceProvider! And guess what, the framework doesn’t automatically load the routes/channels.php file anymore.
  • Making RedirectIfAuthenticated better is now a breeze, all thanks to the framework’s core functionality.
  • The "Authenticate" middleware has become smarter and no longer calls the redirectTo() method for JSON routes. This means no more unnecessary ternary checks.
  • We've done a bit of spring cleaning and removed the EncryptCookies, PreventRequestsDuringMaintenance.php, TrimStrings, TrustHosts, TrustProxies, ValidateCsrfToken, and ValidateSignature middleware from the skeleton structure.
  • The Custom Artisan functionality now fits into Laravel 11 like a glove, meaning you won’t have to manually call the load() method from the console anymore.
  • The removal of the routes/console.php file marks a big step forward. Now you can register closure-based artisan commands exclusively within the console kernel.
  • We’ve done some tidying up and merged several additional migrations into a unified file or got rid of them.
  • The AuthorizesRequests and ValidatesRequests traits are no longer part of the basic controller. Less is more, right?
  • The bootstrap/app.php file has been trimmed down, it now just has three lines of code. Talk about being concise!
  • And lastly, Laravel version 11 has waved goodbye to the exception handler.
 

No more Http/Kernel

Most of the things you used to do in the Kernel, you can now easily do in the bootstrap/app.php.

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
 

Model casts changes

In the latest and greatest release of Laravel, we've got a pretty significant change to how Model casts work. Instead of being just a property, they've evolved into a method definition. But don't worry, it's a change for the better! Why, you ask? Well, this new method-based approach opens up a world of possibilities, like being able to directly call other methods within the casts. How cool is that?

In the Laravel universe, you need to set attribute casting within an Eloquent model. Here's how it looks:

<?php

class SomeModel extends Model
{
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

But wait, there's more! With Laravel 11, you've now got the superpower to define your casting using the casts() method right within your model. This means you can make use of static methods from the class that's in charge of the casting.

Check this out:

<?php

class SomeModel extends Model
{
    protected function casts(): array
    {
        return [
            'foo' => AsCollection::using(ExampleCollection::class),
        ];
    }
}

And did I mention you can also specify your casts as an array? Have a look below:

<?php

class SomeModel extends Model
{
    protected $casts = [
        'foo' => [
            AsCollection::class,
            ExampleCollection::class,
        ],
    ];
 
    protected function casts() : array
    {
        return [
            'foo' => [
                AsCollection::class,
                ExampleCollection::class,
            ],
        ];
    }
}

And the cherry on top? These changes won't break anything in your existing codebase when you transition to Laravel 11. It's all smooth sailing here!

 

New Dumpable Trait

We're here to make things more efficient! We're streamlining the heart of the framework, given that many classes currently have dd or dump methods.

The good news? You can also use this friendly Dumpable trait in your own classes!

<?php
 
use Illuminate\Support\Traits\Dumpable;
use Illuminate\Support\Traits\Conditionable;
 
class Test
{
    use Conditionable, Dumpable;
    // ...
}
 
$test = new Test;
 
// Before:
$test->foo()->bar();
 
// After:
$test->foo()->dd()->bar();
 

Config Changes

In older versions of Laravel, there were multiple config files to juggle, but hooray! Laravel v11 has made things much simpler by getting rid of these files and integrating all the config options. Now, with our trusty .env file, you have a one-stop-shop for all the options you want to set or adjust.

What's more, Laravel 11 has brought with it a nifty new config:publish command. This little helper gives you the power to pull up any config settings you need. How handy is that?

Once you've got your settings sorted, the newly added cascade functionality is here to make your life easier. It lets you sweep away any configurations you don't want to customise. This means a smoother, more tailor-made configuration process for you. For example, if you run artisan config:publish database, you'll get a dedicated configuration just for the database.

 

Routes changes

Hey there! In the usual Laravel setup, you'll stumble upon two main route files: console.php and web.php. If you're thinking of including API routes, no worries! All you need to do is run the php artisan install:api command. Just like that, you'll have your API routes file, and voila! Laravel Sanctum functionality enabled.

Now, if you're into websocket broadcasting, Laravel has got you covered. Simply use the php artisan install:broadcasting command. This little helper is designed to tweak those essential files and settings to let websocket broadcasting shine in your Laravel apps.

These tweaks, small as they might seem, actually mark a big step towards a more modular and customizable application framework. Isn't that exciting?

 

New Once method

The new once helper method in Laravel 11 guarantees consistent values despite multiple calls to an object method.

This function is useful for code that needs to run only once.

<?php

class Helper
{
    public function uuid(): UuidInterface
    {
        return Str::uuid();
    }

    public function uuidOnce(): UuidInterface
    {
        return once(fn (): UuidInterface => $this->uuid());
    }
}
 
$helper = new Helper();
 
foreach(range(1,5) as $helper->uuid()) {
    echo uuid() . "\n";
}

/*
Output:
d40593cb-42f5-4fb4-96f6-54ea334b6fc2
8022ca19-65af-4b43-99b0-43939ef9859b
7f477255-c0dc-4690-87e3-2a48514dd247
d9358da6-c925-470b-8327-fa5fcd7ec84c
7040108a-df41-4198-a698-b59ddaaf31de
*/

foreach(range(1,5) as $helper->uuidOnce()) {
    echo $helper->uuidOnce() . "\n";
}

/*
Output:
64b851e7-72b1-40da-8e36-73d7d29a11c8
64b851e7-72b1-40da-8e36-73d7d29a11c8
64b851e7-72b1-40da-8e36-73d7d29a11c8
64b851e7-72b1-40da-8e36-73d7d29a11c8
64b851e7-72b1-40da-8e36-73d7d29a11c8
*/
 

New up Health Route

Laravel 11 will have a new /up health route. This route triggers a DiagnosingHealthEvent, improving uptime monitoring integration.

This route is defined in the new bootstrap/app.php:

->withRouting(
    web: __DIR__.'/../routes/web.php',
    commands: __DIR__.'/../routes/console.php',
    health: '/up',
)
 

APP_KEY Rotation

In previous Laravel versions, altering your APP_KEY could damage database data. Laravel 11 introduces a smooth rotation that prevents old encrypted data from breaking, thanks to the APP_PREVIOUS_KEYS .env variable. The system will automatically re-encrypt the data with the new key.

 

Console Kernel Removed

We're saying goodbye to the Console Kernel. But don't worry! You'll now be able to define your console commands right in the cozy confines of routes/console.php.

 

Eager Load Limit

Laravel 11 includes the code from the "eager load limit" package:

User::select('id', 'name')->with([
    'posts' => fn($query) => $query->limit(5)
])->get();

Welcome to our comprehensive guide on what's new in Laravel 11. Laravel, a popular PHP framework, has just announced its latest version, Laravel 11, which is packed with exciting new features and improvements. This article will walk you through these updates, helping both beginners and experienced Laravel developers get up to speed with the latest advancements in the framework.

No Support For PHP 8.1 in Laravel 11

Laravel version 11 no longer supports PHP 8.1. This is because, by the time Laravel 11 comes out, PHP 8.2 and 8.3 will be stable and better options.

Few people still want PHP 8.1 when there are improved versions available. But you don't have to switch right away; you could test the new versions first.

You might want to update your apps gradually. But choosing the latest version would be a good choice.

 

Simpler Application Framework

Laravel 11 brought changes to make the structure of a Laravel application clearer and simpler. The aim was to provide a cleaner and more effective starting point for your projects. And it certainly did that.

  • In the friendly AuthServiceProvider, the framework works its magic to discover and sweep away the $policies for you.
  • No need to worry about SendEmailVerificationNotification hanging around in the EventServiceProvider. This is because the base EventServiceProvider has got it covered. Plus, brace yourself for this - Laravel now has auto-event discovery turned on by default.
  • Say goodbye to the BroadcastServiceProvider! And guess what, the framework doesn’t automatically load the routes/channels.php file anymore.
  • Making RedirectIfAuthenticated better is now a breeze, all thanks to the framework’s core functionality.
  • The "Authenticate" middleware has become smarter and no longer calls the redirectTo() method for JSON routes. This means no more unnecessary ternary checks.
  • We've done a bit of spring cleaning and removed the EncryptCookies, PreventRequestsDuringMaintenance.php, TrimStrings, TrustHosts, TrustProxies, ValidateCsrfToken, and ValidateSignature middleware from the skeleton structure.
  • The Custom Artisan functionality now fits into Laravel 11 like a glove, meaning you won’t have to manually call the load() method from the console anymore.
  • The removal of the routes/console.php file marks a big step forward. Now you can register closure-based artisan commands exclusively within the console kernel.
  • We’ve done some tidying up and merged several additional migrations into a unified file or got rid of them.
  • The AuthorizesRequests and ValidatesRequests traits are no longer part of the basic controller. Less is more, right?
  • The bootstrap/app.php file has been trimmed down, it now just has three lines of code. Talk about being concise!
  • And lastly, Laravel version 11 has waved goodbye to the exception handler.
 

No more Http/Kernel

Most of the things you used to do in the Kernel, you can now easily do in the bootstrap/app.php.

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
 

Model casts changes

In the latest and greatest release of Laravel, we've got a pretty significant change to how Model casts work. Instead of being just a property, they've evolved into a method definition. But don't worry, it's a change for the better! Why, you ask? Well, this new method-based approach opens up a world of possibilities, like being able to directly call other methods within the casts. How cool is that?

In the Laravel universe, you need to set attribute casting within an Eloquent model. Here's how it looks:

<?php

class SomeModel extends Model
{
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

But wait, there's more! With Laravel 11, you've now got the superpower to define your casting using the casts() method right within your model. This means you can make use of static methods from the class that's in charge of the casting.

Check this out:

<?php

class SomeModel extends Model
{
    protected function casts(): array
    {
        return [
            'foo' => AsCollection::using(ExampleCollection::class),
        ];
    }
}

And did I mention you can also specify your casts as an array? Have a look below:

<?php

class SomeModel extends Model
{
    protected $casts = [
        'foo' => [
            AsCollection::class,
            ExampleCollection::class,
        ],
    ];
 
    protected function casts() : array
    {
        return [
            'foo' => [
                AsCollection::class,
                ExampleCollection::class,
            ],
        ];
    }
}

And the cherry on top? These changes won't break anything in your existing codebase when you transition to Laravel 11. It's all smooth sailing here!

 

New Dumpable Trait

We're here to make things more efficient! We're streamlining the heart of the framework, given that many classes currently have dd or dump methods.

The good news? You can also use this friendly Dumpable trait in your own classes!

<?php
 
use Illuminate\Support\Traits\Dumpable;
use Illuminate\Support\Traits\Conditionable;
 
class Test
{
    use Conditionable, Dumpable;
    // ...
}
 
$test = new Test;
 
// Before:
$test->foo()->bar();
 
// After:
$test->foo()->dd()->bar();
 

Config Changes

In older versions of Laravel, there were multiple config files to juggle, but hooray! Laravel v11 has made things much simpler by getting rid of these files and integrating all the config options. Now, with our trusty .env file, you have a one-stop-shop for all the options you want to set or adjust.

What's more, Laravel 11 has brought with it a nifty new config:publish command. This little helper gives you the power to pull up any config settings you need. How handy is that?

Once you've got your settings sorted, the newly added cascade functionality is here to make your life easier. It lets you sweep away any configurations you don't want to customise. This means a smoother, more tailor-made configuration process for you. For example, if you run artisan config:publish database, you'll get a dedicated configuration just for the database.

 

Routes changes

Hey there! In the usual Laravel setup, you'll stumble upon two main route files: console.php and web.php. If you're thinking of including API routes, no worries! All you need to do is run the php artisan install:api command. Just like that, you'll have your API routes file, and voila! Laravel Sanctum functionality enabled.

Now, if you're into websocket broadcasting, Laravel has got you covered. Simply use the php artisan install:broadcasting command. This little helper is designed to tweak those essential files and settings to let websocket broadcasting shine in your Laravel apps.

These tweaks, small as they might seem, actually mark a big step towards a more modular and customizable application framework. Isn't that exciting?

 

New Once method

The new once helper method in Laravel 11 guarantees consistent values despite multiple calls to an object method.

This function is useful for code that needs to run only once.

<?php

class Helper
{
    public function uuid(): UuidInterface
    {
        return Str::uuid();
    }

    public function uuidOnce(): UuidInterface
    {
        return once(fn (): UuidInterface => $this->uuid());
    }
}
 
$helper = new Helper();
 
foreach(range(1,5) as $helper->uuid()) {
    echo uuid() . "\n";
}

/*
Output:
d40593cb-42f5-4fb4-96f6-54ea334b6fc2
8022ca19-65af-4b43-99b0-43939ef9859b
7f477255-c0dc-4690-87e3-2a48514dd247
d9358da6-c925-470b-8327-fa5fcd7ec84c
7040108a-df41-4198-a698-b59ddaaf31de
*/

foreach(range(1,5) as $helper->uuidOnce()) {
    echo $helper->uuidOnce() . "\n";
}

/*
Output:
64b851e7-72b1-40da-8e36-73d7d29a11c8
64b851e7-72b1-40da-8e36-73d7d29a11c8
64b851e7-72b1-40da-8e36-73d7d29a11c8
64b851e7-72b1-40da-8e36-73d7d29a11c8
64b851e7-72b1-40da-8e36-73d7d29a11c8
*/
 

New up Health Route

Laravel 11 will have a new /up health route. This route triggers a DiagnosingHealthEvent, improving uptime monitoring integration.

This route is defined in the new bootstrap/app.php:

->withRouting(
    web: __DIR__.'/../routes/web.php',
    commands: __DIR__.'/../routes/console.php',
    health: '/up',
)
 

APP_KEY Rotation

In previous Laravel versions, altering your APP_KEY could damage database data. Laravel 11 introduces a smooth rotation that prevents old encrypted data from breaking, thanks to the APP_PREVIOUS_KEYS .env variable. The system will automatically re-encrypt the data with the new key.

 

Console Kernel Removed

We're saying goodbye to the Console Kernel. But don't worry! You'll now be able to define your console commands right in the cozy confines of routes/console.php.

 

Eager Load Limit

Laravel 11 includes the code from the "eager load limit" package:

User::select('id', 'name')->with([
    'posts' => fn($query) => $query->limit(5)
])->get();

That's all for the new features and updates in Laravel 11. As you can see, Laravel continues to improve and evolve, making it an even more powerful tool for developers. Stay tuned for more updates as they are released.

Happy coding!

Read more:

 

Conclusion

That's all for the new features and updates in Laravel 11. As you can see, Laravel continues to improve and evolve, making it an even more powerful tool for developers. Stay tuned for more updates as they are released.

Happy coding!

Read more:

Ready to fix your code?

Errors

Logs

Crash Reporting

Try for free
We are not pushy
We only send a few emails every month. That's all.
No spam
We only send articles, and helpful tips for developers, not SPAM.