Loading...

What's New in Laravel 11?

Jayram Prajapati  ·   12 Feb 2024
What's New in Larvel 11? New Update, Features & Expert Tips
service-banner

Taylor Otwell, the brain behind this PHP framework, released a first look at Laravel 11 update at Laracon USA in 2023. The Laravel 11 update is going to shake PHP development. The latest exciting news about Laravel 11 Update is that some new features have been shared by the Laravel community. Here, we discuss the upcoming features of Laravel 11 and how it accelerates the development process.

Laravel Upgrade

Nine middleware components are included with Laravel, many of which you would never customise. However, if you want to personalise them, that is moved to the App/ServiceProvider.

For example:
public function boot(): void
{
   EncryptCookies::except(['some_cookie']);
}

What is new in Laravel 11 Update?

Let's dive into latest features of Laravel 11 Update to understand how they can benefit Laravel developers.

1. Sorry For Http/Kernel

This first glance at the Laravel 11 update starts with saying goodbye to the Kernel. Laravel 11 update has removed the dedicated HTTP kernel file and shifted the configuration to the bootstrap/app.php file.

return Application::configure()
   ->withProviders ()
   -›withRouting(
       web: __DIR__.'/../routes/web.php'
       commands: __DIR__.'/../routes/console.php',
   )
   ->withMiddleware(function(Middleware Smiddleware) {
       $middleware->web(append: LaraconMiddleware::class):
   })

Functionality of bootstrap/app.php

  • Application configuration: This file is now responsible for configuring the Laravel 11 application instance using the Application::configure() method. This includes specifying providers, routes, middleware, and other vital aspects.
  • Provider registration: Using ->withProviders(), you register providers that provide essential services to your application like database connections, authentication, caching, etc.
  • Route configuration: With ->withRouting(), you define paths to routing files for web and console routes.
  • Middleware configuration: The ->withMiddleware() method allows you to define and configure middleware that handles incoming HTTP requests. The example you provided shows adding LaraconMiddleware to the web middleware stack.

2. Model casts changes

Second news of Laravel 11 updates is Laravel moves the Model casts from property to method. Currently, model casts are defined as a method rather than a property. _'AsEnumCollection’_

Major Changes:
  • Instead of defining casts as a property array on the model, you now define them within a casts() method. This allows for more dynamic and flexible casting behaviour.
  • You can directly call methods on cast classes within the casts() method, enabling more intricate casting logic.

protected function casts(): array
{
    return [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'options'=› AsEnumCollection::of(UserOption::class),
    ];
}

3. New Dumpable Trait

Laravel 11 update Introduced Dumpable Trait It is used to simplify debugging by providing unified dump() and dd() methods across the framework and your custom classes. The dumpable Trait reduces code duplication. Many Laravel classes implemented separate dd and dump methods. The 'Dumpable' trait consolidates these methods into a single reusable trait.

Major Changes:
  • The Dumpable trait simplifies debugging by offering consistent dd and dump methods across different classes, including custom ones.
  • This code example showcases leveraging the trait in a custom class like Stringable to inspect its state during development conveniently.
  • Remember that ‘dd’ and ‘dump’ can impact performance, so use them responsibly in production environments.
class Stringable implements JsonSerializable, ArrayAccess
{
   use Conditionable, Dumpable, Macroable, Tappable;
 
   str('foo')->dd();
   str('foo')->dump();
  • debug a custom class named Stringable
  • Conditionable: Provides methods for conditional logic on strings.
  • Dumpable: The new trait we're focusing on, enabling dd and dump debugging.
  • Macroable: Allows defining custom methods on the class dynamically.
  • Tappable: It lets you chain methods and modify the object before returning it.

4. Config Changes

Instead of having many config files scattered throughout the project, Laravel 11 simplify this process by removing many of these config files.

Instead, Laravel 11 update adopts a cascading configuration approach, where config options cascade down from higher-level settings to more specific ones. This means that instead of managing separate config files for different environments or components, you can set global defaults and override them.

The '.env file', used for environment-specific configuration, has been expanded to include all the options you want to set for your application. This consolidation simplifies configuration settings management, as everything can now be centralized in the .env file.

Laravel 11 update announces a new 'config:publish' command. This command allows developers to selectively bring back any config options they want to customize or override from the streamlined configuration setup. With the cascade feature, developers can quickly eliminate options that aren't needed, keeping the configuration straightforward.

Example

If you need to bring back specific config files for customization, you can use the config:publish command. For example, if you want to customize the mail configuration:

php artisan config:publish mail

This command will return the mail configuration file (config/mail.php) to your project, allowing you to make specific adjustments.

Key points
  • A single .env file makes managing settings easier and eliminates scattered files.
  • Cascading defaults minimize the need for extensive configuration and streamlining setup.
  • The publishing option allows customization if needed while maintaining cascading benefits.

5. New Once method

A helpful technique is designated as the "once" helper method. This technique does exactly what you need. It guarantees that your unique code runs only once, no matter how many times you ask. The first time you call it, Laravel runs that code. But the next time you call it, instead of rerunning the code, Laravel remembers the result from the first time and just gives it back to you.

$value = once(function () {
    // This code will only run once, no matter how many times you call it
    return expensiveOperation();
});

// Subsequent calls to the once helper will return the cached value
$result = once(function () {
    // This code will not run again, it will return the cached value instead
    return expensiveOperation();
});

When running tests, the memoization function must be cleared after each test to make sure you are working in a new state. You can clean the database using the TestCase class using the Once::flush(); method.

Key points
  • The once helper can be used with both methods and closures.
  • By preventing unnecessary repetitions helps optimize code and potentially improve performance.
  • It eliminates the need for manual checks and flags to enforce single execution, making code cleaner and more concise.

6. Reduced default Migrations

One other slight improvement: In Laravel 11 update, they removed the dates in the migrations. This step is significant for developers who have created projects for years and years.

Previously:
  • Laravel included multiple default migration files with dates like before 2014_01_01_create_users_table.php and 2019_01_01_create_password_resets_table.php.
  • This may appear clunky and may tie migrations to specific Laravel versions.
Now:
  • The dates have been removed from the file names. They showed files with only the names you saved: 0000_create_users_table.php and 0001_00_00_create_password_resets_table.php.
  • This makes operations more manageable.
Key Points
  • Having fewer files makes it easier to manage projects.
  • When the code is simple, it is easier to read and update.
  • By removing dates, the migrations are no longer limited to specific Laravel versions, allowing them to work with a broader range of versions.

7. Routes changes

Previously, Laravel had separate route files for web, API, and broadcasting routes. Now, there will be just two route files: console.php and web.php. You can also enable API routes using php artisan install:api, which will give you the API routes file along with Laravel Sanctum.

Default Route Files for Install

php artisan install:api: Creates an api.php file for API routes and installs Laravel Sanctum for authentication.

php artisan install:broadcasting: Creates a broadcasting.php file for broadcasting routes and installs the necessary components.

Key Points
  • A simplified default configuration makes starting new projects more manageable.
  • This only includes web and console routes by default, aligning with common use cases.
  • Opt-in features allow customization and avoid unnecessary bloat for applications that don't need them.

8. New /up Health Route Endpoint:

Laravel 11 adds a custom endpoint for '/up'. This method is a simple ping for uptime monitoring services like Pingdom or UptimeRobot.

The /up route triggers a special event called "DiagnosingHealthEvent". This event lets you attach your own custom logic, enabling more comprehensive health checks.

Seriously checking database connectivity, cache status, or specific application functionalities beyond one code, "Is it up?"

Here's why you'll love it:
  • Easy setup: No more writing custom code. Just use the built-in route.
  • Super flexible: Customize checks to match your specific needs.
  • Peace of mind: Get detailed health reports to catch issues early.

9. APP_KEY Rotation

Sometimes, data has been encrypted using the old APP_KEY, and then you change it, and the application won't be able to decrypt that data anymore correctly.

New Laravel 11 update also has a solution for this. They update the feature “APP_KEY_Rotation”, which means whenever you rotate API_KEY. Your data is achieved through the use of the APP_PREVIOUS_KEYS.env variable.

Laravel 11 update will notice the change and use the APP_PREVIOUS_KEYS variable to retrieve previously used keys. With this information, Laravel can easily decode data encrypted with the old key and then re-encrypt it with the new key during normal application activities. Key Points
  • Encourages frequent APP_KEY rotation without fear of data loss, resulting in improved security hygiene.
  • Removes the need for manual data re-encryption, minimizing potential application downtime during key rotation.
  • It gives trust that encrypted data is secure even after APP_KEY changes.

10. Console Kernel Gonna Be Removed

(app/Console/Kernel.php) is being removed. This might seem like a big change, but it actually simplifies the definition of console commands. Here's what you need to know:

  • You won't need the App\Console\Kernel class anymore.
  • Defining console commands will be done directly in the routes/console.php file.

If you're upgrading to Laravel 11 from an older version, you'll need to migrate your console commands from app/Console/Kernel.php to routes/console.php. Documentation and community resources will be available to help with this transition.

Key points
  • This change removes the need for a separate class and merges console command registration with other route definitions, making it easier to understand and manage.
  • You can now define console commands using anonymous closures, offering a more concise and expressive way to write your commands.
  • No need to manually call the load method in routes/console.php. Laravel automatically loads all commands defined in this file.

11. Eager Load Limit

Laravel 11 update is also working on eager loading. Developers often deal with native support by limiting the number of eagerly loaded results per parent model. This has been a long-awaited feature, and the Laravel team is finally incorporating it into the core framework.

Previously:
  • Eager loading of all related models for many parent models could lead to performance issues and unnecessary data transfer, especially with large datasets.
  • To limit the number of loaded related models, developers had to rely on third-party packages or workarounds in their code.
With Laravel 11:
  • You can directly specify the number of related models to load for each parent model using a simple syntax eagerly.
  • This feature boosts performance by retrieving only the necessary data and reduces memory usage.
Key Points
  • Avoid loading unnecessary data to improve the performance of your application.
  • Especially beneficial for large datasets and resource-intensive applications.
  • No need for complex workarounds or external packages.

Essence

We hope this explanation clarifies the points regarding the Laravel 11 update release of this feature.

But, This feature is currently under development and slated for release with Laravel 11 update, expected later in Q1, 2024. Stay updated for official documentation and examples closer to the release date.

We wanted to provide a comprehensive experience guide as soon as the Laravel 11 update was released, so we connected with Elightwalk for more technological information.

Jayram Prajapati
Full Stack Developer

Jayram Prajapati brings expertise and innovation to every project he takes on. His collaborative communication style, coupled with a receptiveness to new ideas, consistently leads to successful project outcomes.

Most Visited Blog

Benefits of Shopify App Development for E-commerce

This blog explores the multiple benefits, from commercial and technical advantages to effective management of market factors. Learn how custom Shopify apps contribute to revenue generation, customer retention, and seamless scalability. Uncover the essential skills for developers, delve into market strategies, and understand why Shopify has become the go-to choice for businesses of all sizes

How to Clear Shopping Cart in Magento 2

Discover a quick and simple approach to emptying your Magento 2 shopping basket. Streamline your shopping experience by learning how to easily delete things and refresh your basket.

What is a PWA Development? Beginners' Guide For Your Business

Discover the world of PWA development with comprehensive beginners' guide. Unravel the secrets of Progressive Web Apps and how they can transform your online experience.