Laravel 11 – New Features, Guide, Installation & More

 Laravel 11 – New Features, Guide, Installation & More


Laravel 11, released in March 2024, once again raised the bar in the development world. From a revamped project structure to powerful new tools, the Laravel ecosystem is now equipped with tools like Laravel Forge and Laravel Nova, which integrate seamlessly with the core framework, offering an all-encompassing solution for modern web development.

Laravel 11 empowers developers to build robust and scalable applications with unprecedented efficiency.

In this comprehensive guide, we’ll explore its key features, installation process, and best practices.

Laravel Security and Bug Fixes

According to the Support Policy, Laravel 10 will receive bug fixes until August 6th, 2024, and security fixes until February 4th, 2025. As for Laravel 11, you can expect bux fixes until September 2025 and security fixes until March 2026.

VersionPHPReleaseBug fixes untilSecurity fixes until
108.1 – 8.3February 14, 2023August 6, 2024February 4, 2025
118.2 – 8.3March 12, 2024August 5, 2025February 3, 2026

Why Upgrade to Laravel 11?

It is strongly suggested to upgrade to Laravel 11 for many reasons, mostly because it provides noticeable improvements in speed and security. Laravel 11 now supports PHP 8. 2, which means it can use the newest features and improvements. This helps applications run better and safer.

Laravel 11 boasts significant performance optimizations. From enhanced routing capabilities to improved caching mechanisms, the framework has been optimized to deliver lightning-fast response times and optimal resources.

These improvements convert to a smoother user experience and reduced server loads, making Laravel 11 an ideal choice for high-traffic applications.

What’s New in Laravel 11?

Laravel 11 introduces several significant updates and features that enhance the developer experience and application performance.

PHP 8.2 Support

Developers can leverage PHP 8.2’s readonly classes and disjunctive normal form (DNF) types, which simplify complex type declarations and improve code readability. These advancements, combined with Laravel’s framework updates, enable faster development cycles and more maintainable codebases.

To ensure your Laravel 11 application uses PHP 8.2, update your composer.json file to require PHP 8.2:

  1. // Ensure your Laravel application is using PHP 8.2
  2. // composer.json
  3. {
  4. "require": {
  5. "php": "^8.2"
  6. }
  7. }

Run the following command to apply the changes:

  1. composer update

Query Builder

One notable addition of Larave 11 is the improved query builder, which now supports more advanced SQL capabilities and offers better performance optimizations. This makes it easier for developers to write complex queries efficiently.

  1. // Example of using the enhanced query builder
  2. $users = DB::table('users')
  3. ->select('name', 'email')
  4. ->where('active', 1)
  5. ->whereBetween('created_at', [now()->subMonth(), now()])
  6. ->orderBy('name')
  7. ->get();

Laravel Blade Engine

Laravel 11 includes enhancements to the Blade templating engine, adding new directives and improving existing ones, making it even more powerful and flexible for creating dynamic views.

  1. {{-- Example of a new Blade directive --}}
  2. @datetime($user->created_at)
  3. {{-- Custom Blade directive definition --}}
  4. @directive('datetime')
  5. <?php echo ($expression)->format('m/d/Y H:i'); ?>
  6. @enddirective

Async/Await Syntax

Another significant update in Laravel 11 is the introduction of the “async/await” syntax, which simplifies handling asynchronous tasks.

This feature allows developers to write more readable and maintainable asynchronous code, improving the overall code quality and reducing the chances of bugs related to asynchronous operations.

  1. // Example of using async/await syntax
  2. use Illuminate\Support\Facades\Http;
  3. async function fetchUserData($userId)
  4. {
  5. $response = await(Http::get("https://api.example.com/users/{$userId}"));
  6. return $response->json();
  7. }
  8. // Calling the async function
  9. $userData = fetchUserData(1);

Built-in Authentication System

Laravel 11 has also updated its built-in authentication system, making it more customizable and easier to integrate with third-party authentication providers.

This offers better support for OAuth and OpenID Connect to simplify the process of integrating social logins and other external authentication methods.

  1. // Example of configuring OAuth in Laravel 11
  2. // config/services.php
  3. return [
  4. 'github' => [
  5. 'client_id' => env('GITHUB_CLIENT_ID'),
  6. 'client_secret' => env('GITHUB_CLIENT_SECRET'),
  7. 'redirect' => env('GITHUB_REDIRECT_URI'),
  8. ],
  9. ];

Using Socialite for GitHub Authentication.

  1. use Laravel\Socialite\Facades\Socialite;
  2. Route::get('/login/github', function () {
  3. return Socialite::driver('github')->redirect();
  4. });
  5. Route::get('/login/github/callback', function () {
  6. $user = Socialite::driver('github')->user();
  7. // Handle the authenticated user data
  8. });

Error Handling

The new version offers improvements to the error handling and logging mechanisms. It provides more detailed and actionable error messages, which helps developers diagnose and fix issues more efficiently.

  1. // Example of custom error handling in Laravel 11
  2. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  3. class Handler extends ExceptionHandler
  4. {
  5. public function register()
  6. {
  7. $this->reportable(function (Throwable $e) {
  8. // Custom error reporting logic
  9. Log::error($e->getMessage(), ['exception' => $e]);
  10. });
  11. $this->renderable(function (Exception $e, $request) {
  12. if ($request->wantsJson()) {
  13. return response()->json([
  14. 'error' => 'Something went wrong!'
  15. ], 500);
  16. }
  17. });
  18. }
  19. }

New Helper Functions

Laravel 11 introduces several new helper functions and utilities that streamline common development tasks.

These include enhanced support for file uploadsbetter handling of environment variables, and improvements to the testing framework, making it easier to write and maintain unit and integration tests.

  1. // Example of new helper functions
  2. // Enhanced file upload handling
  3. if ($request->hasFile('avatar')) {
  4. $path = $request->file('avatar')->store('avatars', 'public');
  5. }
  6. // Improved environment variable handling
  7. $apiKey = env('API_KEY', 'default_value');
  8. // Improvements to the testing framework
  9. public function testExample()
  10. {
  11. $response = $this->get('/');
  12. $response->assertStatus(200);
  13. $response->assertSee('Laravel');
  14. }

Key Features of Laravel 11

Now, let’s check out some of the key features of Laravel 11.

1. Slim Skeleton

Laravel 11 features a more streamlined application skeleton. This means a cleaner directory structure and fewer default configuration files. For instance, routes, middleware, and exceptions are now registered in the bootstrap/app.php file.

  1. // bootstrap/app.php
  2. Route::get('/', function () {
  3. return view('welcome');
  4. });

2. New Artisan Commands

Laravel 11 introduces new Artisan commands prefixed with make:xxxxx. These commands streamline the generation of various code components, including classes, traits, enums, and interfaces.

  1. php artisan make:controller WelcomeController

3. Health Check

A new health-check route is available to monitor your application’s overall health. This can be useful for diagnostics and alerting systems.

  1. return Application::configure(basePath: dirname(__DIR__))
  2. ->withRouting(
  3. web: __DIR__.'/../routes/web.php',
  4. commands: __DIR__.'/../routes/console.php',
  5. channels: __DIR__.'/../routes/channels.php',
  6. health: '/up',
  7. )
  8. ->withMiddleware(function (Middleware $middleware) {
  9. //
  10. })
  11. ->withExceptions(function (Exceptions $exceptions) {
  12. //
  13. })->create();

Laravel defines the health route when setting the routes and fires the DiagnosingHealth Event.

  1. use Illuminate\Foundation\Events\DiagnosingHealth;
  2. use Illuminate\Support\Facades\View;
  3. class ApplicationBuilder
  4. {
  5. if (is_string($health)) {
  6. Route::middleware('web')->get($health, function () {
  7. Event::dispatch(new DiagnosingHealth);
  8. return View::file(__DIR__.'/../resources/health-up.blade.php');
  9. });
  10. }
  11. }

4. Dumpable Trait

The Dumpable trait simplifies debugging by providing a consistent way to inspect variables within your code. You can include this trait in your classes for easy dd and dump functionality.

  1. use Illuminate\Support\Traits\Conditionable;
  2. use Illuminate\Support\Traits\Dumpable;
  3. class Address
  4. {
  5. $address = new Address;
  6. $address->setThis()->dd()->setThat();
  7. }

5. Limit Eager Loading:

Laravel 11 limits the number of records eagerly loaded with a relationship. This can improve performance for large datasets.

  1. $users = User::with(['posts' => function ($query) {
  2. $query->latest()->limit(10);
  3. }])->get();

6. Casts Method

Model casting is now defined within the casts() method instead of the $casts property. This improves readability and separation of concerns.

  1. class User extends Model
  2. {
  3. protected function casts()
  4. {
  5. return [
  6. 'birthday' => 'date',
  7. ];
  8. }
  9. }

7. once() Method

The once()method allows you to run a closure only once within the application’s lifecycle. This can be useful for initialization tasks or setup logic.

  1. once(function () {
  2. // Code that should run only once
  3. });

8. API and Broadcasting: Installed Optionally

In Laravel 11, the routes/api.php file is no longer present by default, and Sanctum is not pre-installed. To add API scaffolding, you can use the command php artisan install.

This command will create and register the routes/api.php file in bootstrap/app.php and install Laravel Sanctum.

The only additional step required is to add the Laravel\Sanctum\HasApiTokens trait to the User model.

Similarly, broadcasting has also become an optional installation. To set it up, use the command

  1. php artisan install

9. New Welcome Page

Laravel 11 introduces a new welcome page. The images below showcase its appearance in both light and dark modes.

-Light mode

-Dark mode

Deprecated Features

While Laravel 11 introduced many new features, some functionalities have been deprecated:

  • PHP 8.1 Support: Laravel 11 no longer supports PHP 8.1. The minimum required version is now PHP 8.2.
  • Default Configuration Files: Several default configuration files have been removed, promoting a more modular approach.
  • Optional API and Broadcasting: API and broadcasting functionalities are now installed optionally during project creation.

Summary

Laravel 11 is more than just an update. It has a range of enhancements that boost developer productivity, improve application performance, and strengthen security.

Beyond technical improvements, Laravel 11 also continues to prioritize developer experience. The framework’s comprehensive documentation and supportive community ensure that developers, whether beginners or experts, have the resources they need to excel.

Q. What version of PHP is Laravel 11?

A. Laravel 11 requires PHP 8.2 or higher.

Q. What is the difference between Laravel 10 and Laravel 11?

A. Laravel 11 introduces a more minimalist application skeleton and removes default folders like app/Consoleapp/Exceptions, and app/Http/Middleware, and registers routes, middlewares, and exceptions in bootstrap/app.php.

Additionally, Laravel 11 does not include routes/api.php or Sanctum by default, and both API and broadcasting setups require explicit installation commands.

There is also a new welcome page with light and dark modes.

Q. Should I update to Laravel 11?

A. You should update to Laravel 11 for its streamlined and minimalist application skeleton, improved structure with centralized registrations in bootstrap/app.php, and easy installation commands for API and broadcasting setups.

Comments