DEV Community

Cover image for What’s New in Laravel 11?
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on • Edited on

What’s New in Laravel 11?

Streamlined Directory Structure

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();
Enter fullscreen mode Exit fullscreen mode

Laravel 11 simplifies its directory structure, reducing the initial complexity for developers. Notably, Kernel.php files have been removed, and middleware can now be directly added in the bootstrap/app.php file.

Improved Routing Efficiency

Route::prefix('user')->group(function () {
    Route::get('/dashboard', function () {
        // Dashboard view
    });
    Route::get('/setting', function () {
        // Setting view
    });
});
Enter fullscreen mode Exit fullscreen mode

You can now define route groups more succinctly, this might look familiar, but under the hood, Laravel 11 optimizes these routes, making your application a tad quicker. It’s like giving your routes a little caffeine boost!

Enhanced Eloquent ORM

protected $casts = [
    'is_active' => 'boolean',
    'launch_date' => 'datetime',
    'options' => 'array',
    'custom_object' => CustomClass::class,
];
Enter fullscreen mode Exit fullscreen mode

There’s a new feature called “Eloquent Casts” that allows you to convert attributes to common data types or even your custom classes more smoothly. This is super handy for working with data transformations directly in your model.

Custom Casts in Laravel 11

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class OptionsCast implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes)
    {
        return new Options(json_decode($value, true));
    }

    public function set($model, string $key, $value, array $attributes)
    {
        return $value->toArray();
    }
}

class User extends Model
{
    protected $casts = [
        'options' => OptionsCast::class,
    ];
}
Enter fullscreen mode Exit fullscreen mode

In this example, Options is a custom class we’ve defined to work with our user options. The OptionsCast class ensures that whenever we access the options attribute on a User model, it’s returned as a Options object, and when we set it, it’s automatically serialized into the appropriate JSON format for storage.

Laravel Scout Database Engine

$blogs = Blog::search('Laravel 11')->get();
Enter fullscreen mode Exit fullscreen mode

Laravel Scout, the driver-based full-text search solution for Eloquent, now includes a database engine out of the box. This is perfect for those who don’t need a heavy search engine like Algolia or Elasticsearch for smaller projects.

Improved Authorization Responses

Gate::define('update-post', function ($user, $post) {
    return $user->id === $post->user_id
                ? Response::allow()
                : Response::deny('You do not own this post.');
});
Enter fullscreen mode Exit fullscreen mode

Laravel 11 introduces a more intuitive way to handle authorization responses. Now, when a policy or gate denies access, you can provide a custom error message directly. This small change allows for more descriptive feedback to users when they’re not allowed to perform certain actions, improving the overall user experience.

Tailwind CSS Pagination Views

{{ $posts->links() }}
Enter fullscreen mode Exit fullscreen mode

For the front-end folks, Laravel 11 ships with Tailwind CSS pagination views out of the box. If you’re riding the Tailwind wave, you’ll appreciate this addition. No more wrestling with custom pagination styles unless you want to!

Queue Improvements

public function handle()
{
    // Your job logic here
}

public function failed(Throwable $exception)
{
    // Called when the job fails
}

public $tries = 1;
public $backoff = 30; // Delay in seconds
Enter fullscreen mode Exit fullscreen mode

Imagine you have a job that needs to retry on failure but with a specific delay and up to a maximum number of attempts. this setup provides more control over job retries and handling failures, making your application more resilient.

New Testing Features

$response = $this->get('/api/post');

$response->assertJson(fn (AssertableJson $json) =>
    $json->where('id', 1)
         ->where('title', 'Laravel 11')
         ->etc()
);
Enter fullscreen mode Exit fullscreen mode

Testing is an integral part of the development process, and Laravel 11 introduces new testing features that make it easier to ensure your application works as expected. One such feature is enhanced HTTP client assertions, which allow for more expressive and comprehensive tests for your external HTTP requests.

Blade Component Tags

<x-alert type="error" :message="$message" />
Enter fullscreen mode Exit fullscreen mode

This new syntax for component tags not only improves readability but also streamlines the process of passing data to components.

Laravel 11: The once Method

$value = once(function () {
    return config('app.name');
});
Enter fullscreen mode Exit fullscreen mode

The once method is a simple yet powerful tool for optimizing your application. It promotes cleaner, more efficient code by ensuring that expensive operations are not unnecessarily repeated. Plus, it’s incredibly easy to use and integrate into your existing Laravel projects.

New Dumpable Trait in Laravel 11

use Illuminate\Support\Traits\Dumpable;

class User extends Model
{
    use Dumpable;
}
...

$model = User::find(1);
$model->dump();

...
$model->dd();
Enter fullscreen mode Exit fullscreen mode

The Dumpable trait allows you to easily dump and die (dd) or just dump (dump) the properties of any Eloquent model or any class that uses this trait, directly from the object itself. This is particularly useful when you want to quickly inspect the data structure of your models or any other objects during development without resorting to external debugging tools or verbose logging methods.

Top comments (1)

Collapse
 
kortizti12 profile image
Kevin

Hey there,

Great article on the new features in Laravel 11! The breakdown of the simplified directory structure and the improved routing efficiency was super clear. I especially appreciated the examples showcasing the enhanced Eloquent ORM and custom casts – those are going to be game-changers for my projects.

My colleague Guilherme also recently wrote a piece on Laravel 11 that you might find interesting. He goes into more depth on some of the core updates and the new application skeleton. You can check it out here: scalablepath.com/php/laravel-11

Thanks for sharing your insights, and keep the Laravel content coming!