The Latest on Laravel 11: Features and Updates Unveiled

Suraj ShettySuraj Shetty
5 min read

Laravel 11: A Streamlined Framework for Modern Web Development

Laravel 11, released in March 2024, is the newest major version of the popular PHP web development framework. It continues Laravel's tradition of offering a strong foundation for creating modern web applications, emphasizing a great developer experience and clean code. Laravel 11 arrived with a focus on streamlining the development process and improving core functionalities.

  1. once() Method

    Laravel 11 introduces a new one helper method that guarantees you'll always receive the same value, regardless of how many times you call an object method. The once function is useful for ensuring certain code runs only once.

class User extends Model
{
    public function details(): array
    {
        return once(function () {
            // Code Logic

            return $details;
        });
    }
}

// Assuming you have two User instances: $suraj and $ravi

$suraj->details();
$suraj->details(); // cached result from previous line...

$ravi->details(); // Not using $suraj cached results, because $ravi !== $suraj
$ravi->details(); // cached result from previous line...
  1. Limit Eager Loading

    Laravel 11 introduces the ability to limit the number of records that are eagerly loaded directly, without needing any external packages. Before Laravel 11, you had to use a separate package called Eloquent Eager Limit by Jonas Staudenmeir for this functionality. Now, you can simply use the limit method to control how many records are eagerly loaded with relationships.

$user = User::with('posts')->limit(5)->get();
  1. Casts Method

    Starting with Laravel 11, casts are defined in the protected casts() the method instead of the protected $casts property. This change won't break anything. It's important to note that the casts() method takes precedence over the $casts property.

class User extends Model
{
    protected function casts()
    {
        return [
            'created_at' => 'datetime:Y-m-d H:i:s',
        ];
    }
}
  1. Slimmer Application Structure

    Laravel 11 streamlines the project structure for a cleaner and more focused development experience.

    Removed folders:

    • app/Console (Artisan commands now in routes/console.php)

    • app/Exceptions (Exception handling in bootstrap/app.php)

    • app/Http/Middleware (Middleware registration in bootstrap/app.php

    • This reduces boilerplate and improves code organization.

    app/
      |- Http/
      |   |- Controllers/
      |   |   |- Controller.php  (Base controller for your application)
      |   |- Kernel.php           (Handles HTTP requests to the application)
      |- Models/
      |   |- User.php              (Example model representing a user)
      |- Providers/
      |   |- AppServiceProvider.php (Registers core application services)
      |- ...                       (Other application-specific models, controllers, etc.)
    bootstrap/
      |- app.php                   (Centralizes configuration for routes, middleware, exceptions)
      |- providers.php             (Registers framework service providers)
    config/
      |- ...                       (Application configuration files)
    database/
      |- migrations/              (Migration files for database schema changes)
      |- factories/                (Model factories for generating test data)
      |- seeds/                    (Seeder files for populating the database with test data)
    public/
      |- assets/                    (Static assets like CSS, JavaScript)
      |- index.php                  (Laravel application entry point)
    resources/
      |- lang/                      (Localization files for translations)
      |- views/                     (Blade templates for application views)
    routes/
      |- web.php                    (Web application routes)
      |- api.php                   (Optional: API routes)
      |- console.php                (Artisan console commands)
    tests/
      |- Feature/                   (Feature tests for application functionality)
      |- Unit/                      (Unit tests for individual components)
      |- ...                       (Other test directories)
    .env
    composer.json
    package.json
  1. API and Broadcasting: Optional Installation

    Laravel 11 doesn't come with a routes/api.php file, and Sanctum isn't included by default. You can add the API scaffolding by using the php artisan install:api command.

    Running this command creates the routes/api.php file, adds it to bootstrap/app.php, and installs Laravel Sanctum. You just need to add the Laravel\Sanctum\HasApiTokens trait to your User model.

    Broadcasting can also be added as needed. To set up broadcasting, use the php artisan install:broadcast command.

  2. New Command: make: example

    Laravel 11 comes with new make: artisan commands. Now, you can create enums, interfaces, and classes.

php artisan make:enum
php artisan make:class
php artisan make:interface
  1. Dumpable Trait

    Laravel 11 introduces a new Dumpable trait. Its purpose is to take the place of the existing dd() and dump() methods in many of the framework's classes. This makes code debugging easier for both users and package creators.

use Illuminate\Support\Traits\Dumpable;

class any
{
    use Dumpable;

    // logic code
}

$any= new any;

$any->method()->method(); 
$any->method()->dd()->method(); // new feature
  1. Health Check

    This method leverages Laravel's event system to perform health checks and potentially trigger custom logic or notifications based on the results.

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

    With Laravel 11, there are a couple of new default settings introduced. The testing framework has been updated to Pest following a poll by Taylor on X (Twitter), where the majority preferred Pest. For those new to testing, there's a course titled Testing in Laravel 11 For Beginners that primarily uses Pest syntax, with PHPUnit examples also provided. Additionally, the default database has been switched to SQLite, as detailed in the pull request SQLite for local dev and further explained in the YouTube video Upcoming Laravel 11: SQLite as Default Database. For users interested in changing the default database driver to MySQL, there's an article that guides you through the process.

  2. Removed Some Config Files

    This change has a backstory. Initially, when Taylor introduced a slimmer skeleton, all config/ files were removed. However, Taylor wasn't satisfied with this change and introduced a slimmer config version. As a result, if you compare the config/ folder of Laravel 10 with Laravel 11, you'll notice that the following files are missing in Laravel 11: config/broadcasting.php, config/cors.php, config/hashing.php, config/sanctum.php, and config/view.php.

Conclusion:

We will cover more features in our next blog post. In the meantime, try out Laravel 11 and explore some excellent packages we've recently reviewed in this blog post: https://surajshetty.hashnode.dev/top-5-essential-laravel-packages-you-need-in-2024. Here, you can find information about great packages and tools.

Thanks For Reading This Blog.

0
Subscribe to my newsletter

Read articles from Suraj Shetty directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Suraj Shetty
Suraj Shetty

Passionate backend developer with a strong foundation in designing and implementing scalable and efficient server-side solutions. Specialized in creating robust APIs and database management. Committed to staying ahead in technology trends, I have a keen interest in DevOps practices, aiming to bridge the gap between development and operations for seamless software delivery. Eager to contribute to innovative projects and collaborate with like-minded professionals in the tech community. Let's connect and explore the possibilities of creating impactful solutions together! #BackendDevelopment #DevOps #TechInnovation