Laravel has been a popular PHP framework for many years. It is elegant and scalable, and has become one of the go-to frameworks for PHP developers and businesses. Laravel 9 is the recent release, and it includes a number of new features.
Previously, new Laravel versions happened every six months, resulting in a considerable amount of inquiries, rude remarks, and uncertainty regarding Laravel’s updated release process. With the release of Laravel 9 in February 2022, the framework transitioned to a 12-month major release cycle. This article delves into Laravel 9’s important features, so; let’s get started!
What Is Laravel?
Laravel is an open-source PHP framework known for its exceptional syntax. It uses an MVC framework for building various apps with PHP, ensuring complete efficiency. Laravel constantly works to improve its saved features, which is why it contributes to new functions and releases.
It also had multiple updates that have improved its efficiency. The recent version, Laravel 9, includes a number of new features. The new version has reduced the developers’ tasks and provides complete convenience. Let us know about some more Laravel features.
Interesting Features of Laravel 9
If you’re new to this framework, here is a compiled list of the Laravel features to help you get a better grasp.
1) Eloquent accessors/mutators improvement
Taylor Otwell introduced Eloquent accessors/mutators, a feature that allows developers to handle database queries using PHP syntax rather than writing SQL code, which can be time-consuming.
In Laravel 8, accessors and mutators must be defined using the model’s get and set prefixes. However, in Laravel V9, you can declare the prefix with a single non-prefixed phrase using the IlluminateDatabaseEloquentCastsAttribute. You can now acquire and set characteristics with only one method call.
Example:
use Illuminate\Database\Eloquent\Casts\Attribute;
public function username (): Attribute
{
return new Attribute(
get: fn ($value) => strtoupper($value),
set: fn ($value) => $value,
);
}
In this example, the accessor will cache and return the username value. The attribute function accepts two arguments. The first is for get, and the second is for setting the attribute. Overall, Version 9 will make the procedure easier and faster.
2) Enum attribute casting
Mohamed Said helped with Enum casting. It is only available in PHP versions 8.1+. You can now define enums in the enum file, as well as any enum types you choose. All of this is easily found in the enum file in App/Enums/. You also need to declare a return type in the file, which you can do by specifying attributes and enums in the model’s $casts property array.
Once you have defined your casts on the model, it will automatically cast the desired attribute from an enum file. For additional information, you can visit Enum Casting.
3) Implicit Route Bindings With Enums
Enums are now supported by PHP 8.1. Laravel 9.x allows you to type-hint an Enum on a route declaration, and Laravel will only apply the route if the route component matches a valid Enum value in the URI. Otherwise, it will instantly return an HTTP 404 error.
Example:
In App/Enums/Category:
enum Category: string
{
case Fruits = ‘fruits’;
case People = ‘people’;
}
In Route File :-
Route:: get (‘/categories/{category}’, function (Category $category) {
return $category->value;
});
You can now select a route that is only used if the category route segment includes fruits or peoples. Otherwise, you will receive an HTTP 404 response.
4) Forced Scoping Of Route Bindings
In previous versions of Laravel, scoping required the key of the parent eloquent model, however it does not appear that scoping was used. However, with Laravel 9, there is a function called the scope bindings method for defining a route.
When utilizing norms to presume the relationship’s name on the parent, Laravel will automatically range the query to fetch the nested models.
Even if no key is provided, the Scope bindings method will instruct the child model. Check out the following formula to do so:
Example:
use App\Models\Post;
use App\Models\User;
Route:: get (‘/users/{user}/posts/{post}’, function (User $user, Post $post) {
return $post;
})->scopeBindings();
Check the code below for the same.
Route:: scopeBindings ()->group (function () {
Route:: get (‘/users/{user}/posts/{post}’, function (User $user, Post $post) {
return $post;
});
});
5) Controller Route Groups
Luke Downing is credited with creating Laravel 9’s most potent feature, controller route groups. To create the routes and their functions for a controller, you must first utilize the controller function for controller routes.
That method will be automatically invoked by that controller. You can prevent the controller from being used twice by using controller route grouping.
Example:
use App\Http\Controllers\OrderController;
Route::controller(OrderController::class)->group(function () {
Route::get(‘/orders/{id}’, ‘show’);
Route::post(‘/orders’, ‘store’);
});
6) Full-Text Indexes / Where Clauses
“Where” clauses and full-text indexes were contributed by Dries Vints and Taylor Otwell. Full-text indexes can now be created in MySQL and PostgreSQL by introducing the full-text technique into column definitions. They use the WhereFullText and/or WhereFullText methods for the query.
These methods are converted by Laravel into the SQL for the supporting database system. Applications that use MySQL will generate a MATCH AGAINST clause.
Example:
$table->text(‘bio’)->fullText();
$users = DB::table(‘users’)->whereFullText(‘bio’, ‘web developer’)->get();
7) Rendering Inline Blade Templates
Creating inline Blade templates was provided by Jason Beggs . Blade templates are used to transform a string into valid HTML when you need to transfer data to HTML.
You are welcome to utilize the blade facades render approach. Two inputs will be accepted by the render method: a blade string as the first and an optional array of data as the second.
Example:
use Illuminate\Support\Facades\Blade;
return Blade::render(‘Hello, {{ $name }}’, [‘name’ => ‘Julian Bashir’]);
8) Checked / Selected Blade Directives
Blade directions were picked, verified, and contributed by Ash Allen and Taylor Otwell. The selection of the checkbox and dropdown menu required the writing of a specific condition in the previous edition.
The @checked and @selected blade components for selection, which we define in those components, allow Laravel version 9 to overcome this issue by only selecting data if a specific condition is true.
@checked: if the given condition is true, it will echo checked.
Example:
< input type=”checkbox” name=”active” value=”active” @checked(old(‘active’, $user-> act
@selected:- it will select a particular option if the provided condition is true.
Example:
< select name=”version” >
@foreach ($product->versions as $version)
< option value=”{{ $version }}” @selected(old(‘version’) == $version) >
{{ $version }}
< /option >
@endforeach
< /select >
9) Bootstrap 5 Pagination Views
If you’ve ever experienced pagination in your projects, you understand how helpful having a built-in framework to handle it is. Laravel has automatic pagination, which removes the need for manual pagination.
However, Laravel 9.0 makes this work even easier. The pagination view in Laravel 9 will be created with Bootstrap 5. You can invoke the useBootstrapFive function in the boot method of your App\Providers\AppServiceProvider class.
10) Improved Validation Of Nested Array Data
Steve Bauman made improvements to the nested array input validation. When assigning the rule to an attribute, you might occasionally need to validate an array element and retrieve its value.
Laravel 9 offers a solution for this problem as well by introducing the Rule:foreach method. This method accepts a closure, which will be called with the attribute’s value and explicit, fully expanded attribute name for each iteration of the array attribute that is being validated.
Example:
use App\Rules\HasPermission;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
$validator = Validator::make($request->all(), [
‘companies.*.id’ => Rule::forEach(function ($value, $attribute) {
return [
Rule::exists(Company::class, ‘id’),
new HasPermission(‘manage-company’, $value),
];
}),
]);
11) Improved Ignition Exception Page
Spatie’s open-source exceptions debugging page, Ignition, has undergone a complete redesign with a few additional features to provide users a host of benefits. Features like customisable “open in editor” functionality, light/dark themes, and much more are included in Laravel release 9.
12) Improved route: list CLI Output
The command-line interface (CLI) of Laravel is another noteworthy feature. It spares you from having to use the command line to navigate through directories and files in order to develop or modify any component of Laravel. It can also help you to use the command line to communicate with your databases.
Version 9 improved things even further by introducing a new route list design in the command line interface.
13) Test Coverage Using Artisan Command
There’s a new coverage option in Laravel 9. The test coverage will be instantly visible on the terminal thanks to a new artisan test coverage option. The proportion of code that has been tested will be shown with the help of it.
php artisan test –coverage
It also has a minimum option that you may use to specify the minimum coverage level to enforce.
php artisan test –coverage –min=80.3
14) Anonymous Stub Migration
Laravel configures anonymous stub migration as the default behavior when you run the most recent migration function:
Laravel 8.37 introduces the anonymous migration feature in response to this GitHub issue. Several migrations with the same class name may cause issues if you try to rebuild the database entirely. The most recent version of the stub migration functionality eliminates the possibility of migration class name collisions.
As of Laravel 8.37, the platform supports anonymous class migration files; in Laravel 9, this will be the default behavior.
Example:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up() {
Schema::table(‘users’, function (Blueprint $table) {
$table->string(‘first_name’)->nullable();
});
}
};
Future of Web Development With Laravel
Web development has a bright future, mostly because of the work of Laravel developers. We anticipate seeing more companies use Laravel-based web development in 2024 with a stronger focus on user experience, scalability, and security. For your web development requirements, it’s critical to find a Laravel developer with the necessary expertise, experience, and creativity. Our team of very talented Laravel developers at Xelent Solutions have all of these qualities to make your project skyrocket in future. Contact us today!
Conclusion
With the combination of these features, Laravel has achieved widespread popularity among developers as a platform for the development of web applications. Because of its user-friendliness, advanced security features, scalability, and robust community support, Laravel is a framework that is both reliable and efficient for the development of customized online applications.