Exploring Laravel 11: What’s New in the Latest Release

Happy Laravel 11 day! With the release of Laravel 11, the Laravel ecosystem continues to push boundaries and bring exciting new features to developers. In this blog post, we’ll take a closer look at what Laravel 11 has to offer.

Minimum PHP v8.2 Support

Laravel 11 sets the bar higher by requiring a minimum of PHP v8.2, ensuring that developers can leverage the latest features and optimizations of the PHP language.

Laravel Reverb: Real-Time Communication Made Easy

One of the headline features of Laravel 11 is the introduction of Laravel Reverb, a first-party WebSocket server designed specifically for Laravel applications. With Reverb, developers can achieve seamless real-time communication between clients and servers.

// Example of using Laravel Reverb
use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
    return $user->canJoinRoom($roomId);
});

Streamlined Directory Structure

Laravel 11 brings a significant improvement in project organization by streamlining the directory structure. This simplification not only reduces file counts but also enhances the clarity and maintainability of Laravel applications.

Key Changes:

  1. Controllers No Longer Extend Anything by Default:
    In previous versions of Laravel, controllers extended a base controller class by default. However, in Laravel 11, controllers no longer extend anything by default, providing developers with greater flexibility and control over their controller implementations.
   // Example of a controller in Laravel 11
   class UserController extends Controller
   {
       public function index()
       {
           // Controller logic
       }
   }
  1. Removal of Middleware Directory:
    Laravel 11 removes the middleware directory from the default directory structure. Middleware customization is now moved to the App/ServiceProvider, simplifying the middleware management process.
   // Example of middleware customization in a service provider
   public function boot(): void
   {
       EncryptCookies::except(['some_cookie']);
   }
  1. Consolidation of Middleware Customization:
    Previously, Laravel included several middleware that were often left untouched by developers. With Laravel 11, middleware customization is consolidated within the App/ServiceProvider, allowing developers to easily customize middleware if necessary.
   // Example of middleware customization in a service provider
   public function boot(): void
   {
       EncryptCookies::except(['some_cookie']);
   }

These changes contribute to a cleaner and more intuitive directory structure, making Laravel applications easier to understand and maintain. Developers can now focus on building robust features without getting bogged down by unnecessary boilerplate code.

Model Casts Changes

In Laravel 11, model casts undergo significant enhancements, providing developers with more flexibility and control over how attribute values are casted and manipulated within Eloquent models.

Enhanced Method-Based Definition

In previous versions of Laravel, model casts were defined as properties within the Eloquent model class. However, in Laravel 11, model casts are defined as methods, offering greater versatility and enabling more complex casting logic.

// Example of defining model casts as methods in Laravel 11
protected function casts(): array
{
    return [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'options' => AsEnumCollection::of(UserOption::class),
    ];
}

With this method-based approach, developers can encapsulate additional logic within the casting methods, such as calling other methods or performing custom transformations on attribute values.

Improved Readability and Maintainability

By defining model casts as methods, Laravel 11 enhances the readability and maintainability of Eloquent models. Developers can now easily locate and understand the casting logic for specific attributes within the model class, leading to cleaner and more organized codebases.

Seamless Integration with Other Features

The method-based definition of model casts seamlessly integrates with other Laravel features, such as custom casts and attribute manipulation methods. Developers can leverage the full power of Eloquent models while maintaining a consistent and intuitive API.

// Example of using a custom cast with method-based model casts in Laravel 11
protected function casts(): array
{
    return [
        'options' => AsEnumCollection::of(UserOption::class),
    ];
}

New Dumpable Trait

To streamline debugging processes, Laravel 11 introduces the Dumpable trait, allowing for consistent and convenient dumping of data within the framework and in custom classes.

// Example of using the Dumpable trait
$str = 'foo';
$str->dump(); // Dump the string value

Config Changes

One of the standout features in Laravel 11 is the revamped configuration system, which offers greater flexibility and customization options for developers. This overhaul brings a streamlined approach to managing configuration files, allowing developers to optimize their applications for efficiency and simplicity.

Removal and Re-Inclusion of Configuration Files

During the development of Laravel 11, all configuration files were initially removed from the default Laravel installation. However, a few weeks before release, Taylor Otwell, the creator of Laravel, made the decision to reintroduce a slimmed-down version of the config files in a default Laravel install. This decision was driven by the desire to give developers more control over their application’s configuration while minimizing unnecessary clutter.

Slimming Down Configuration Files

Laravel 11 introduces a unique approach to configuration file management, enabling developers to create leaner and more focused configuration files tailored to their specific needs. The framework internally merges user-defined configuration files with its default configuration, allowing developers to override default settings and add custom options seamlessly.

For instance, consider the following config/app.php file within a Laravel 11 application:

<?php

return [
    'timezone' => 'Europe/Paris',
    'custom_option' => 'foo'
];

In this example, the resulting configuration would include all core app configuration options along with the overridden timezone setting and the additional custom_option.

Targeted Configuration Slimming

Laravel 11 empowers developers to further slim down their configuration files by selectively removing top-level options they do not use. This selective slimming process ensures that only essential configuration options are retained, reducing noise and improving overall code clarity.

Additionally, Laravel performs intelligent merging of nested options, such as database.connections and filesystem.disks, allowing developers to include only the drivers they use without cluttering their configuration files.

For example, a config/database.php file in a Laravel 11 application may look like this:

<?php

return [
    'connections' => [
        'mysql_2' => [
            // MySQL 2 configuration...
        ],
    ]
];

By slimming down configuration files in this manner, developers can create cleaner, more maintainable codebases that focus on essential customizations without unnecessary bloat.

New Once Method

The addition of the once helper method ensures that a method returns the same value regardless of how many times it’s called, offering greater control over code execution.

// Example of using the once helper method
$value = once(function () {
    return expensiveOperation();
});

Slimmed Default Migrations

Default migrations in new Laravel applications have been slimmed down, reducing redundancy and improving project cleanliness.

Routes Changes

Laravel 11 introduces changes to routes management, with only two default route files (console.php and web.php).

In addition to the default web.php and console.php route files, Laravel 11 introduces opt-in mechanisms for defining API routes and websocket broadcasting routes. Developers can now use the php artisan install:api and php artisan install:broadcasting commands to generate dedicated route files for API routes and websocket broadcasting, respectively.

# Example of generating API routes in Laravel 11
php artisan install:api

# Example of generating websocket broadcasting routes in Laravel 11
php artisan install:broadcasting

This opt-in approach allows developers to explicitly define API and broadcasting routes when needed, without cluttering the main route files with unnecessary route definitions.

New Health Route

A new /up health route is included in Laravel 11, providing improved uptime monitoring capabilities for applications.

Application::configure(basePath: dirname(__DIR__))
    ->withProviders()
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        // api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        // channels: __DIR__.'/../routes/channels.php',
        health: '/up', 
    )
    // ...

APP_KEY Rotation

Enhancing security, Laravel 11 introduces graceful rotation for the APP_KEY, ensuring compatibility with existing encrypted data.

// Example of rotating APP_KEY in Laravel 11
php artisan key:rotate

Named Arguments

Laravel 11 introduces support for named arguments, providing developers with a more expressive and readable syntax.

// Example of using named arguments in Laravel 11
User::create(name: 'John', email: '[email protected]');

Eager Load Limit

Integration of the « eager load limit » package allows for more granular control over eager loading in Laravel applications.

// Example of using eager load limit in Laravel 11
User::select('id', 'name')->with([
    'articles' => fn($query) => $query->limit(5)
])->get();

New Artisan Commands

Laravel 11 adds new Artisan commands for the quick creation of classes, enums, interfaces, and traits, streamlining the development process.

php artisan make:class
php artisan make:enum
php artisan make:interface
php artisan make:trait

New Welcome Page

With significant updates to Laravel, developers can expect a new welcome page when creating a new Laravel application.

Conclusion

Laravel 11 brings a host of exciting changes and enhancements to the popular PHP framework, empowering developers to build modern, scalable, and maintainable applications with ease. From streamlined configuration and route management to improved model casting and artisan commands, Laravel 11 delivers a wealth of features designed to streamline development workflows and boost productivity.

With its focus on simplicity, flexibility, and performance, Laravel 11 continues to push the boundaries of PHP development, offering developers a delightful and intuitive development experience. Whether you’re building a small web application or a large-scale enterprise solution, Laravel 11 provides the tools and resources you need to bring your ideas to life.

Release Date

Laravel 11 was officially released on March 12, 2024, marking a significant milestone in the evolution of the Laravel framework. With its groundbreaking features and enhancements, Laravel 11 sets the standard for modern PHP development, empowering developers to build robust, feature-rich applications that stand the test of time.


Publié

dans

, ,

par

Étiquettes :

Commentaires

Laisser un commentaire