
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.
Experience Seamless Laravel Hosting on Cloudways!
Elevate Your Laravel Development and unlock the full potential of Laravel with Cloudways hosting.
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.
Version | PHP | Release | Bug fixes until | Security fixes until |
10 | 8.1 – 8.3 | February 14, 2023 | August 6, 2024 | February 4, 2025 |
11 | 8.2 – 8.3 | March 12, 2024 | August 5, 2025 | February 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:
// Ensure your Laravel application is using PHP 8.2 // composer.json { "require": { "php": "^8.2" } }
Run the following command to apply the changes:
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.
// Example of using the enhanced query builder $users = DB::table('users') ->select('name', 'email') ->where('active', 1) ->whereBetween('created_at', [now()->subMonth(), now()]) ->orderBy('name') ->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.
{{-- Example of a new Blade directive --}} @datetime($user->created_at) {{-- Custom Blade directive definition --}} @directive('datetime') <?php echo ($expression)->format('m/d/Y H:i'); ?> @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.
// Example of using async/await syntax use Illuminate\Support\Facades\Http; async function fetchUserData($userId) { $response = await(Http::get("https://api.example.com/users/{$userId}")); return $response->json(); } // Calling the async function $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.
// Example of configuring OAuth in Laravel 11 // config/services.php return [ 'github' => [ 'client_id' => env('GITHUB_CLIENT_ID'), 'client_secret' => env('GITHUB_CLIENT_SECRET'), 'redirect' => env('GITHUB_REDIRECT_URI'), ], ];
Using Socialite for GitHub Authentication.
use Laravel\Socialite\Facades\Socialite; Route::get('/login/github', function () { return Socialite::driver('github')->redirect(); }); Route::get('/login/github/callback', function () { $user = Socialite::driver('github')->user(); // Handle the authenticated user data });
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.
// Example of custom error handling in Laravel 11 use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { public function register() { $this->reportable(function (Throwable $e) { // Custom error reporting logic Log::error($e->getMessage(), ['exception' => $e]); }); $this->renderable(function (Exception $e, $request) { if ($request->wantsJson()) { return response()->json([ 'error' => 'Something went wrong!' ], 500); } }); } }
New Helper Functions
Laravel 11 introduces several new helper functions and utilities that streamline common development tasks.
These include enhanced support for file uploads, better handling of environment variables, and improvements to the testing framework, making it easier to write and maintain unit and integration tests.
// Example of new helper functions // Enhanced file upload handling if ($request->hasFile('avatar')) { $path = $request->file('avatar')->store('avatars', 'public'); } // Improved environment variable handling $apiKey = env('API_KEY', 'default_value'); // Improvements to the testing framework public function testExample() { $response = $this->get('/'); $response->assertStatus(200); $response->assertSee('Laravel'); }
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.
// bootstrap/app.php Route::get('/', function () { return view('welcome'); });
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.
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.
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();
Laravel defines the health route when setting the routes and fires the DiagnosingHealth Event.
use Illuminate\Foundation\Events\DiagnosingHealth; use Illuminate\Support\Facades\View; class ApplicationBuilder { if (is_string($health)) { Route::middleware('web')->get($health, function () { Event::dispatch(new DiagnosingHealth); return View::file(__DIR__.'/../resources/health-up.blade.php'); }); } }
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.
use Illuminate\Support\Traits\Conditionable; use Illuminate\Support\Traits\Dumpable; class Address { $address = new Address; $address->setThis()->dd()->setThat(); }
5. Limit Eager Loading:
Laravel 11 limits the number of records eagerly loaded with a relationship. This can improve performance for large datasets.
$users = User::with(['posts' => function ($query) { $query->latest()->limit(10); }])->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.
class User extends Model { protected function casts() { return [ 'birthday' => 'date', ]; } }
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.
once(function () { // Code that should run only once });
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
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.
How To Install Laravel 11 on Cloudaways Server
Installing Laravel on a Cloudways server is simple and easy. Here’s a step-by-step guide:
Step 1: Launch a Server on Cloudways
- Log in to your Cloudways account.
- Click on “Launch” to create a new server.
- Select Laravel Application.
- Choose your preferred server provider (e.g., AWS, Google Cloud, DigitalOcean), size, and location.
- Click “Launch Now” to set up your server.
Step 2: Access the Server
- Once the server is ready, go to the Servers tab in the Cloudways dashboard.
- Select the server you just created.
- To log in to the server via an SSH client, use the “Master Credentials” provided in the Access Details section.
- Click Servers on the top-left to access the server management.
- Click Settings & Packages.
- You’ll see the currently installed PHP version. Click the edit button on its side to upgrade from PHP 7.x to PHP 8.2 or PHP 8.3.
- Open the SSH terminal and run the Composer command to start the Laravel 11 installation process on the server.
Let’s start with the Cloudways SSH terminal. Go to the application public_html folder and type the following Laravel installation command:
command composer create-project laravel/laravel:^11.0 test-app.
This will create a new Laravel 11 application named test-app in the public_html directory.
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/Console
, app/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.
Sandhya Goswami
Sandhya is a contributing author at Cloudways, specializing in content promotion and performance analysis. With a strong analytical approach and a keen ability to leverage data-driven insights, Sandhya excels in measuring the success of organic marketing initiatives.