Laravel 11: New changes and features

Laravel 11

What’s New in Laravel 11: Features and Changes

Laravel 11 has arrived with a slew of features and changes, offering developers a leaner and more efficient framework for building web applications. Let’s dive into the exciting features and changes introduced in this latest release:

1. Slimer Application Skeleton:

Laravel 11 brings a refined application structure, decluttering and redefining how Laravel applications are organized. This revamp aims to provide developers with a leaner and more efficient starting point for their projects.

2. The All-New bootstrap/app.php File:

In Laravel 11, the bootstrap/app.php file undergoes a significant transformation, emerging as a central hub for configuring various aspects of your application. This revamped file provides developers with unprecedented control over critical components such as routing, middleware, service providers, and exception handling.

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();

3. Simplified Service Providers:

Say goodbye to juggling multiple service providers! Laravel 11 consolidates all service provider functionality into a single AppServiceProvider, promoting a tidier and more organized codebase. The `AppServiceProvider` handles much of the functionality previously managed by separate service providers. For example, event discovery is now enabled by default, eliminating the need for manual event registration. However, developers still have the flexibility to manually register events, route model bindings, or authorization gates in the `AppServiceProvider` if needed.

4. Optional API and Broadcast Route Files:
In Laravel 11, the default presence of the api.php and channels.php route files has been reevaluated. Furthermore, recognizing that not all applications necessitate these routes, they are no longer included by default. However, developers can easily opt-in to these features using simple Artisan commands.

php artisan install:api
 
php artisan install:broadcasting

5. Streamlined Middleware:

In Laravel 11, a significant optimization has been made to the middleware structure, resulting in a more streamlined and efficient application. Previously, new Laravel applications included nine middleware, each performing various tasks such as request authentication, input string trimming, and CSRF token validation.

However, in Laravel 11, these middleware have been moved into the framework itself, reducing the overhead and complexity of your application’s structure. Instead of manually including middleware files, developers can now customize middleware behavior directly within the `bootstrap/app.php` file.

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(
        except: ['stripe/*']
    );
 
    $middleware->web(append: [
        EnsureUserIsSubscribed::class,
    ])
})

6. Scheduling Tasks:
In Laravel 11, scheduling tasks is made more intuitive and convenient with the introduction of the `Schedule` facade. In addition to that, developers can now define scheduled tasks directly within the `routes/console.php` file, eliminating the need for a separate console “kernel” class. Here’s an example of scheduling a task to send emails daily.

use Illuminate\Support\Facades\Schedule;
 
Schedule::command('emails:send')->daily();

7. Exception Handelling:

Exception handling in Laravel 11 follows a similar pattern to routing and middleware customization. Developers can now customize exception handling directly from the `bootstrap/app.php` file instead of a separate exception handler class. This consolidation reduces the overall number of files included in a new Laravel application and enhances code organization.

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->dontReport(MissedFlightException::class);
 
    $exceptions->report(function (InvalidOrderException $e) {
        // ...
    });
})

8. Simplified Base Controller in Laravel 11

In Laravel 11, the base controller class undergoes a significant simplification, aligning with the framework’s philosophy of providing a lean and flexible foundation for web development. Let’s explore the changes made to the base controller class:

1. Removal of Extending Internal Controller Class:
Unlike previous versions of Laravel where the base controller extended Laravel’s internal Controller class, Laravel 11 simplifies this structure. Likewise, the base controller no longer extends any internal class, allowing for greater customization and reduced dependency on framework-specific implementations.

2. Removal of AuthorizesRequests and ValidatesRequests Traits:
In Laravel 11, the AuthorizesRequests and ValidatesRequests traits are removed from the base controller. Instead, laravel encourages developers to include these traits in their application’s individual controllers as needed.This approach enhances modularity and allows for more granular control over authorization and validation logic within specific controller contexts.

Example:

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;

abstract class BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    // Your custom controller logic goes here
}

By removing the AuthorizesRequests and ValidatesRequests traits from the base controller, Laravel 11 promotes a cleaner and more focused controller structure, where each controller can include only the functionality it requires. Consequently, leading to better code organization and maintainability.

9. Per-Second Rate Limiting:

In Laravel 11, the framework introduces support for “per-second” rate limiting, enhancing its rate limiting capabilities beyond the previous “per-minute” granularity. Developers can now enforce rate limits at a finer level, controlling the frequency of requests more precisely. This improvement allows for better scalability, performance, and traffic management in Laravel applications. In addition to that, implementing per-second rate limiting is straightforward using the perSecond() method provided by the Limit class within the RateLimiter::for() method. Overall, this enhancement empowers developers to build more resilient and responsive applications capable of handling varying levels of traffic efficiently.

RateLimiter::for('invoices', function (Request $request) {
    return Limit::perSecond(1);
});

10. Automatic Password Rehashing:

In Laravel 11, automatic password rehashing enhances security by automatically updating bcrypt-hashed passwords as the bcrypt work factor adjusts. This feature ensures that password security remains robust over time without inconveniencing users, reinforcing Laravel’s commitment to proactive security measures.

11. New Artisan Commands

In Laravel 11, Taylor Otwell introduces a set of new Artisan commands to expedite the creation of various types of classes, including enums, interfaces, and traits. These commands simplify the development process by providing quick shortcuts for generating essential components of Laravel applications. The newly added Artisan commands are:

  • php artisan make:class: Generates a new class.
  • php artisan make:enum: Creates a new enumeration class.
  • php artisan make:interface: Generates a new interface.
  • php artisan make:trait: Creates a new trait.

These commands streamline class creation, enabling developers to focus more on building application logic rather than spending time on boilerplate code.

12. Model Casts Improvements

In Laravel 11, Nuno Maduro contributes improvements to model casts, allowing for more streamlined and fluent cast definitions. Laravel 11 now supports defining model casts using a method rather than defining model casts. This enhancement offers a more elegant and expressive approach, especially when using casts with arguments.

Here’s an example demonstrating the new method for defining model casts:

protected function casts(): array
{
    return [
        'options' => AsCollection::using(OptionCollection::class),
        // Additional casts can be defined here
    ];
}

In conclusion, with its focus on simplicity, efficiency, and security, Laravel 11 continues to push the boundaries of web development, making it an essential tool for developers seeking to create modern and scalable applications. Moreover, Laravel 11 offers a wealth of features to explore and leverage in your projects, ensuring a smooth and productive development experience. Upgrade to Laravel 11 today and unlock the full potential of your web applications with new features and changes.

Source: https://laravel.com/docs/11.x/releases

Leave a Reply

Your email address will not be published. Required fields are marked *