What’s New in Laravel 11: Upcoming Changes
Exploring the Latest Features in Laravel 11: What Web Developers Need to Know
Table of contents
- Improved Routing Efficiency
- Enhanced Eloquent ORM
- Laravel Scout Database Engine
- Improved Authorization Responses
- Tailwind CSS Pagination Views
- Queue Improvements
- Octane Compatibility Enhancements
- New Testing Features
- Improved Support for Inertia.js
- Blade Component Tags
- Laravel 11: The once Method
- Understanding New Dumpable Trait in Laravel 11
- Things to consider before moving up to Laravel 11
- Wrapping Up
Hey web developers! Laravel 11 news has just dropped, and it’s packed with some cool new features that are definitely worth a chat. If you’re into Laravel like I am, you’re probably eager to know what’s new and how it can make our lives easier. So, let’s dive in, shall we? And yes, we’ll do it in our usual casual way with plenty of code examples to keep things clear and fun.
Improved Routing Efficiency
One of the first things you’ll notice in Laravel 11 is the improved routing efficiency. The team has worked on making the routing process faster and more intuitive. For example, you can now define route groups more succinctly.
Route::prefix('admin')->group(function () {
Route::get('/dashboard', function () {
// Dashboard view
});
Route::get('/profile', function () {
// Profile view
});
});
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
Eloquent ORM, the heart of Laravel’s database interaction, has received some love too. 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.
protected $casts = [
'is_active' => 'boolean',
'launch_date' => 'datetime',
'options' => 'array',
'custom_object' => CustomClass::class,
];
This means less boilerplate in your controllers or services for data manipulation. Just define it once, and Eloquent handles the rest. Neat, right?
Custom Casts in Laravel 11
Laravel 11 allows for more nuanced control over data casting, enabling the use of custom classes for casting. This means you can define exactly how attributes should be cast when they are set or retrieved from the model.
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class AddressCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return new Address(...json_decode($value, true));
}
public function set($model, string $key, $value, array $attributes)
{
return json_encode([
'line1' => $value->line1,
'city' => $value->city,
'country' => $value->country,
]);
}
}
And then you would use this cast in a model like so:
class User extends Model
{
protected $casts = [
'address' => AddressCast::class,
];
}
With this setup, whenever you access the address
attribute on a User
model, it will be automatically instantiated into an Address
object, and when you set it, it will be converted back into a JSON representation for storage in the database.
Let’s consider a practical example where we use a custom cast to handle a complex settings field within a user model. We want this settings field to be easily accessible as a PHP object when we’re working with it in our application, but stored as JSON in our database.
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class SettingsCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return new Settings(json_decode($value, true));
}
public function set($model, string $key, $value, array $attributes)
{
return $value->toArray();
}
}
class User extends Model
{
protected $casts = [
'settings' => SettingsCast::class,
];
}
In this example, Settings
is a custom class we’ve defined to work with our user settings. The SettingsCast
class ensures that whenever we access the settings
attribute on a User
model, it’s returned as a Settings
object, and when we set it, it’s automatically serialized into the appropriate JSON format for storage.
Laravel Scout Database Engine
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.
$articles = Article::search('Laravel 11')->get();
It’s as simple as that. Scout uses your default database for full-text search, making it easier to set up and use, especially for quick prototypes or small applications.
Improved Authorization Responses
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.
Gate::define('update-post', function ($user, $post) {
return $user->id === $post->user_id
? Response::allow()
: Response::deny('You do not own this post.');
});
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
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!
{{ $users->links() }}
And just like that, you get beautiful, Tailwind-styled pagination. It’s these little quality-of-life improvements that make Laravel such a joy to work with.
Queue Improvements
Laravel’s queue system is a powerful tool for deferring time-consuming tasks, such as sending emails or processing images. In Laravel 11, the queue system has been enhanced with better failure handling and simplified syntax for defining complex workflows.
Imagine you have a job that needs to retry on failure but with a specific delay and up to a maximum number of attempts. Laravel 11 makes this incredibly straightforward:
public function handle()
{
// Your job logic here
}
public function failed(Throwable $exception)
{
// Called when the job fails after the specified attempts
}
public $tries = 3;
public $backoff = 60; // Delay in seconds
This setup provides more control over job retries and handling failures, making your application more resilient.
Octane Compatibility Enhancements
Laravel Octane supercharges your application’s performance by serving your application using high-powered servers like Swoole and RoadRunner. Laravel 11 brings compatibility improvements and optimizations for Octane, ensuring that your Laravel applications run even faster, especially under heavy load.
The framework’s compatibility with Octane means that you can now leverage concurrent requests and long-lived application instances without worrying about common pitfalls like memory leaks or instance pollution.
New Testing Features
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.
$response = $this->get('/api/user');
$response->assertJson(fn (AssertableJson $json) =>
$json->where('id', 1)
->where('name', 'John Doe')
->etc()
);
This fluent syntax for asserting against JSON structures makes API testing more intuitive and less error-prone.
Improved Support for Inertia.js
For those embracing the modern JavaScript ecosystem, Laravel 11 improves support for Inertia.js, a framework for building single-page applications without much of the complexity of traditional SPAs. This includes smoother integration for passing data from Laravel to your Inertia.js components and improved session management for SPA authentication.
Blade Component Tags
Blade, Laravel’s templating engine, now supports a more intuitive way of working with components. You can use a simpler tag syntax for including components, which makes your Blade files cleaner and more readable.
<x-alert type="error" :message="$message" />
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
It’s a fantastic addition for those scenarios where you want to ensure a piece of code within your application is only executed once per request, no matter how many times it’s called. This can be super useful for optimizing performance and avoiding redundant operations.
Let’s say you have a configuration loader in your app, and this loader is called multiple times across different parts of your application. Normally, each call would execute the loader again, potentially leading to unnecessary performance overhead. With Laravel 11’s once
method, you can drastically streamline this process. Here’s a simple example to illustrate how you might use it:
$value = once(function () {
// Imagine this is an expensive operation, like loading config from a file or database
return config('app.name');
});
// No matter how many times you call `once` with the same closure,
// it will only execute the first time and return the cached result afterwards.
In this scenario, the anonymous function passed to once
will execute the first time once
is called. If any subsequent calls are made to once
with the same closure during the same request lifecycle, it will return the result from the first execution without running the closure again.
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.
Practical Use Cases
Loading configuration values that don’t change during the request lifecycle but are used in multiple places.
Database queries that fetch the same data in different parts of your application. You can use
once
to ensure the query is executed just once and then reuse the result.Integrations with third-party services, where you need to retrieve data like API keys or settings only once per request.
Understanding New Dumpable Trait in Laravel 11
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.
To use the Dumpable
trait in your Eloquent models or any other class, you first need to import the trait from its namespace and then use it within your class definition like so:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Traits\Dumpable;
class YourModel extends Model
{
use Dumpable;
// Your model's properties and methods
}
Once your model uses the Dumpable
trait, you can easily dump the model’s properties using:
$yourModelInstance = YourModel::find(1);
$yourModelInstance->dump();
Or, if you want to stop the execution of the script after dumping the model’s properties, you can use:
$yourModelInstance->dd();
This feature is particularly useful in development environments where you often need to quickly inspect the current state of an object. For example, when troubleshooting why a certain piece of data is not displaying correctly in your views, or when checking the structure of data being returned by a complex query.
Things to consider before moving up to Laravel 11
Laravel 11 drops the support for PHP 8.1 and will support PHP 8.2 and up.
Laravel 11 Documentation: After the launch, Laravel 11 documentation should be available here.
No official date is announced for laravel 11 release yet but the expectation is by the end of Q1 2024.
Wrapping Up
Laravel 11 continues to polish the framework, making our development process smoother, faster, and more enjoyable. Whether it’s backend improvements like routing and Eloquent enhancements or front-end goodies like Tailwind pagination, there’s something for every Laravel enthusiast in this release.
The post What’s New in Laravel 11: Upcoming Changes appeared first on TechTales.