Laravel is a popular and powerful open-source PHP framework widely used by developers to create websites and web applications. It is easy to understand and implement. Laravel was again in the news with the release of the Laravel 11 version in March 2024. This release creates curiosity among developers about its exciting features and updates.
If you want to learn about the latest features and updates of Laravel 11, You are in the right place. No need to worry, we are here to help you. In this blog post, we are going to explore the exciting new features and significant updates in Laravel 11.
Exploring the Latest Updates in Laravel 11?
Laravel 11 is equipped with so many useful updates and excellent features that simplify the development process for developers and enhance the overall performance of apps.
Improved Query Builder:
Laravel 11 has come up with an improved Query Builder, which is equipped with advanced SQL and ensures optimized performance. These advancements empower developers to write complex queries more effectively and 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();
Async/Await Syntax:
Async/Await Syntax is another significant enhancement in Laravel 11, which makes it easier for you to manage asynchronous tasks efficiently. With this feature, you can easily write readable and maintainable asynchronous code, which in turn enhances the code quality and eliminates the bugs while performing asynchronous-related 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);
Support for PHP 8.2
With Laravel 11, developers can take advantage of PHP 8.2’s readonly classes and DNF (Disjunctive Normal Form) types, which help improve code readability and ease complex type declarations. These enhancements, along with Laravel updates, streamline the development process and maintain codebases.
// Ensure your Laravel application is using PHP 8.2
// composer.json
{
"require": {
"php": "^8.2"
}
}
Run this command, “composer update,” to make changes.
Blade Templating Engine:
Laravel 11 introduced an enhanced “Blade Templating Engine” with additional directives, which helps you create dynamic views easily.
{{-- Example of a new Blade directive --}}
@datetime($user->created_at)
{{-- Custom Blade directive definition --}}
@directive('datetime')
format('m/d/Y H:i'); ?>
@enddirective
New Built-in Authentication System:
Another significant introduction to Laravel is an updated built-in authentication system, which is more customizable than it was before. Most importantly, it can be seamlessly integrated with third-party authentication providers.
This improved system also allows OAuth and OpenID Connect to make the process of integrating social logins and external authentication practices much easier.
// 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'),
],
];
New Helper Functions:
There are numerous new helper functions in Laravel 11, which help accelerate normal development tasks.
New helper functions provide robust support for file uploads, manage environment variables effectively, and bring more improvements to the testing framework. As a result, you can simplify the writing and maintenance of 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');
}
Improved Error Handling:
In Laravel 11, you will find significant improvements in the error handling and logging mechanisms. It provides you with error messages in detail, allowing you to analyze issues properly and resolve them quickly.
// 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);
}
});
}
}
What New Features Does Laravel 11 Offer?
New features in Laravel 11 aim to enhance developers’ experience and streamline the development cycle. Let’s explore the key features of this advanced Laravel version.
New Artisan Commands:
Laravel 11 unveiled the latest artisan commands, which now can be conveniently prefixed with Make:xxxxx. With these commands, you can quickly generate code components, such as enums, traits, classes, and interfaces.
php artisan make:controller WelcomeController
Slimmer Skeleton:
Laravel 11 introduced a robust and faster application skeleton. As a result, your directory structure will be clean without any clutter with fewer default configuration files. Now, you can register middleware, routes, and exceptions in the bootstrap/app.php file.
// bootstrap/app.php
Route::get('/', function () {
return view('welcome');
});
Dumpable Trait:
The Dumpable trait allows you to perform an inspection of variables within the code, which makes debugging much easier. You can achieve seamless DD and dump functionality by incorporating the dumpable trait in your classes.
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\Dumpable;
class Address
{
$address = new Address;
$address->setThis()->dd()->setThat();
}
Casts Method:
With Laravel 11, you can now define the model casting within the casts() in a proper way, and you don’t need to specify it in the $casts, resulting in improved readability and separation of queries.
class User extends Model
{
protected function casts()
{
return [
'birthday' => 'date',
];
}
}
Improved Health Check Route:
Laravel has come up with an improved health check route, which keeps an eye on the health of your apps and is beneficial to both 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();
During the process of creating routes and firing the DiagnosingHealth Event, Laravel 11 helps you specify the health route.
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');
});
}
}
Restricted Eager Loading:
Laravel 11 sets a limit on the number of records that can be eagerly loaded with a relationship. As a result, datasets can perform better.
$users = User::with(['posts' => function ($query) {
$query->latest()->limit(10);
}])->get();
API and Broadcasting:
A significant improvement in Laravel 11 is the elimination of the routes/api.php file. Moreover, Sanctum is no longer pre-installed. You can utilize the php artisan install command for the addition of scaffolding.
By using this command, you can set and register the routes/api.php file in bootstrap/app.php while installing Laravel Sanctum.
To complete the setup, you need to add the Laravel\Sanctum\HasApiTokens trait to the user model.
With Laravel 11, it is now optional to install the broadcasting. You can use the php artisan install command for its setup.
php artisan install
Once() Method:
With the once() method, you can run a closure only once within your app. This helps you initialize tasks and set up logic
once(function () {
// Code that should run only once
});
Custom Artisan Integration:
Laravel 11 allows you to generate custom artisan commands, which enhance the functionality of this command-line tool.
With the defined custom artisan commands, you can perform repetitive tasks during development automatically. These tasks include the creation of boilerplate code, deployment of apps, and running custom data migrations. This will save you time and allow you to focus on enhancing the prime functionality within your app.
On top of that, you can package and share the custom artisan commands as reusable libraries, which enhance team collaboration and quicken the development process.
Updated Welcome Page:
One of the key highlights of Laravel 11 is the new welcome page, which has both light and dark modes, making it more attractive.
Pest and SQLite as Defaults:
The pest and SQLite are set as the default options in Laravel 11. The pest is used to test units and features. A clean syntax of pest makes the testing process natural and delightful.
SQLite is set as a default database in Laravel 11, which is used for local development. This eliminates the need for installing the external database, which leads to a seamless development setup.
Conclusion
Laravel 11 is undoubtedly the most powerful version that came up with so many significant updates, which empower developers to enhance their productivity, ensure security, and boost the performance of applications.
The new updates and features aim at simplifying developers’ tasks and enhancing their experience. It offers flexibility when building web applications and streamlines the development process. You can leverage these new features and build a scalable web app easily and quickly.