Introducing Laravel, from Laravel 6 to Laravel 9
Back in the day, programmers used to write Web applications from scratch, writing their own user authentication, routing, session management, caching, etc.
This approach meant that developers had more to learn when they switched to a project with a completely new architecture or paradigm. Employers also had to spend more resources on training new software developers.
Application Frameworks like Laravel have become widely adopted to speed-up development time. There's less time spent on reinventing the wheel and more time available for innovation.
Since 2011, Laravel has become the most popular PHP Web application Framework. Laravel has changed quite a lot over the years. If you are new to Laravel development or you have been working with a different development framework for a while, you can learn about the most important changes introduced in recent versions of Laravel below.
What is Laravel?
Laravel is a PHP Web application framework, which means that it is designed to provide the standard components of a Web application and to enforce software engineering standards to improve the quality of software applications.
Laravel has an MVC (Model View Controller) software architecture, which means that it separates code dedicated to processing a request (Controller), code for the Business Logic (the Model part, where interaction with a database can take place), and code for the User Interface.
The purpose of an MVC architecture is to improve file management and code organization.
Laravel uses a tool called Artisan, located in the root directory of the application to run CLI commands which may for example create a new Entity class. You often see Laravel CLI commands starting with the word artisan, so do not panic it's just Laravel.
For instance, this command uses the Artisan tool to add a Job class to the application and create a Job.php file in the app/http/Models directory:
artisan make:job
When a Web client makes a request to a website, a server must process the request and return a response which is, in most cases an HTML page. Everything that goes on under the hood in a PHP framework like Laravel is designed to either process a request, with the required security protocols, or give you tools to build faster.
Laravel Facade and Service Providers
One of the peculiarities of Laravel is the use of Facade and Helper Functions to access application objects.
Think of Facades as nicknames that can be used anywhere in the code. For example, Auth is the nickname for any implementation of the Authentication logic. Instead of creating an Authentication object, you simply summon it using its nickname or Facade, and Laravel's Service Container will serve an instance of the Authentication class you need.
Helper Functions are the function version of a Facade, they return an instance of a particular class to help you access objects in your code through the all-powerful Laravel Service Container.
Understanding the Facade paradigm
Laravel uses Service Providers to know which class is connected to a Facade. One of the challenges for PHP programmers who have not worked with the Facade paradigm before is to understand that in Laravel, a service called the Service Container can serve instances of classes.
In standard procedural programming, the programmer has to explicitly instantiate objects and submit them to another object as an argument. The role of Laravel's Service Container is to do as much of this fetching and instantiating of objects as possible, to reduce repetitive code.
Blade, the template engine, not the vampire
Laravel uses a template engine called Blade to parse template files and create the HTML files which are served to Web clients through the Internet.
Laravel extensions
Laravel can be extended with packages. Many of these packages are ready to be installed. All you need is a simple command and the PHP package manager Composer.
This command will add a package called breeze into your Laravel application.
composer require laravel/breeze --dev
Using Eloquent with Laravel
Eloquent is the Object Relational Model (ORM) used by Laravel to query the database and automate the repetitive queries used for inserting, selecting, updating, and deleting data.
Given a User class, it is assumed that the corresponding table in the database is called users. The query to select 10 users ordered by their username is written in PHP using Eloquent syntax, so there's no need for the developer to know SQL as well.
$user = User::addSelect(['id','username'])
->orderBy('username')
->limit(10)
->get();
What you need to do to build a Laravel Web application
In order to build a standard PHP Web application with Laravel you roughly need to do the following:
- Install Laravel
- Write or generate the Service Providers which Laravel will use to find your application classes
- Write or generate your application classes
- Write or generate the routes which Web clients will use to make requests
- Customize user authentication settings
- Write database connection settings
- Write template files used to generate HTML files
Laravel can run on any server that runs PHP, including Windows and Linux servers.
Now let's review the main changes that have been made in Laravel from version 6 to version 9.
Main changes introduced in Laravel version 6
Better database subqueries
Laravel 6 introduced a better way to handle subqueries with Laravel's Eloquent. In Laravel 6, subqueries could be handled by a separate entity.
// Laravel 5.8: Select 10 customers with last invoice date
$customers = Customer::select(['id','name', 'last_invoice_date' => function($query) {
$query->select('created_at')
->from('invoices')
->whereColumn('customer_id', 'customers.id')
->orderBy('id', 'DESC')
->limit(1);
}])
->orderBy('id', 'DESC')
->limit(10)
->get();
// Laravel 6
$lastInvoice = Invoice::select('created_at')
->whereColumn('customer_id', 'customers.id')
->orderBy('id', 'DESC');
$customer = Customer::addSelect(['id','name', 'invoice_date' => $lastInvoice])
->orderBy('id', 'DESC')
->limit(10)
->get();
Job Middleware
Since Laravel 6 it is easier to inject your own code before a background task is executed. This Middleware code is contained in its own file, according to the single responsibility principle of SOLID.
Lazy database queries
Laravel 6 introduced the possibility to perform select queries in the database in small batches, to save the memory available and improve application performance.
// Laravel 5.8: selecting all customers at once
$customers = Customer::select('id', 'name')
->orderBy('name')
->all();
// Laravel 6: selecting customers in batches
$customers = Customer::select('id', 'name')
->orderBy('name')
->cursor();
$customers->each(function($user) {
// do something
});
Laravel 6 introduced Ignition, a debugger that displays reports in Blade views. Ignition offers many benefits over previous releases, such as improved Blade error file, line number handling, code editing, and an improved user experience.
Vapor, a system administration, and deployment service
From version 6, Laravel became compatible with Vapor. Vapor is an auto-scaling administration and deployment platform which runs on the AWS Lambda serverless infrastructure. Vapor is fully automated and takes care of all aspects of deploying a Laravel application in the cloud: Web server configuration, SSL certificates, database administration, Cloudfront CDN, SQS queues, Redis clusters, etc.
Vapor has made the need for a system administrator redundant and reduced the cost of running a Laravel application in the Cloud.
Main changes introduced in Laravel version 8
JetStream
Laravel version 8 introduced Laravel JetStream, an application scaffolding with basic out-of-the-box functionalities that most Web applications use: Log in and registration, email verification, two-factor authentication (2 FA), Session Management, etc.
More Eloquent
Laravel 8 introduced a new syntax for Eloquent Model factories, used for testing. In Laravel 8, factories are classes that extend the base Laravel factory class Illuminate\Database\Eloquent\Factories\Factory, and the object created is defined in a method called definition.
In previous versions, a factory object was used for creating objects, and the new object was defined with a Closure.
User factory in Laravel 7.x:
use Faker\Generator as Faker;
use Illuminate\Support\Str;
$factory->define(App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
User factory in Laravel 8:
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
Database Migrations squashing
Laravel 8 introduced Migration squashing, a feature that condenses all database migration files into a single SQL file. This means that instead of having to review many files which made small changes to the database, all these instructions could be added to a single file.
Job batches
Job Batching is another major feature that was released in Laravel version 8 to allow several jobs to be performed in the background.
Better syntax for rate limiting
The syntax for rate limiting was updated in Laravel 8. Rate limiting is a feature that limits the number of times an operation is allowed for a particular period, usually a minute. Rate limiting greatly reduces the ability to guess a password by trying a large number of combinations.
Rate limiting is implemented in 2 steps. First, define a rate limiter in app/Providers/RouteServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(10);
});
Then the pre-configured rate limiter is applied to a group of routes in routes.php
Route::middleware(['throttle:login'])->group(function () {
Route::post('/login', function () {
Route::post('/register', function () {
Maintenance management
The maintenance mode management was updated with the replacement of an allowed IP list with a maintenance mode bypass token.
When an application is put into maintenance mode, an override token is specified:
php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"
The application can then be accessed, while in maintenance mode, by appending the token to its URL: https://boostlane.com/1630542a-246b-4b66-afa1-dd72a4c43515
Namespace of controllers
In Laravel 8, the namespace of controllers was no longer automatically added by Laravel and had to be set manually. This change was made to avoid adding the namespace twice to a controller. The namespace property in app/Providers/RouteServiceProvider.php was set to null by default.
In route files like routes.php (older versions) or web.php, the namespace of the controller should be declared first with the use keyword.
// routes/web.php
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);
Main changes introduced in Laravel version 9
PHP 8 please
Laravel 9 includes Symfony 6 components, and Symfony 6 requires PHP 8 or above.
Anonymous stub migrations
Laravel 9 also introduced anonymous stub migrations, which means there's no need to specify a class name when writing a migration.
The migration creation command can now omit the migration name.
php artisan make:migration
Use of PHP 8 syntax
Laravel 9 is fully compatible with php 8 and it uses php 8 string functions like str_contains(), str_starts_with(), and str_ends_with().
A query builder interface
Laravel 9 also introduced a common query builder interface from QueryBuilder, EloquentBuilder, and EloquentRelation. This change was introduced to facilitate type hinting, refactoring, and static analysis.
As we can see from these changes, the core Laravel features have remained more or less the same over the years. A developer who built applications with Laravel 5 or 6 should be able to find their way around Laravel 9 with little difficulty.
We will learn in future posts how to build a Web application with PHP 8 and Laravel 9.
Our Standard Review
Date created: 16 Aug 2024 05:55:14
Critical Evaluation:
The article presents a coherent overview of Laravel, a popular PHP web application framework, and its evolution over recent versions. The arguments made about the advantages of using frameworks like Laravel are logical and well-supported by examples. The text effectively highlights how Laravel simplifies development tasks, allowing developers to focus on innovation rather than repetitive coding tasks.
However, the article could strengthen its arguments by providing more specific examples of how Laravel improves productivity compared to traditional coding methods. While it mentions the benefits of using MVC architecture and features like Eloquent ORM, it lacks real-world case studies or statistics that demonstrate these improvements in a measurable way.
The article appears to be fair and objective, focusing on the framework's features without overtly promoting it over other frameworks. However, it could benefit from acknowledging some limitations or challenges associated with Laravel, such as potential performance issues in large applications or the learning curve for new developers.
In the real world, the ideas presented in the article suggest that adopting frameworks like Laravel can lead to faster development cycles, reduced training costs for new developers, and ultimately, a more efficient software development process.
Quality of Information:
The language used in the article is mostly clear and accessible, making it suitable for a broad audience, including those who may not have extensive technical knowledge. Technical terms, such as MVC (Model View Controller) and ORM (Object Relational Model), are introduced but could be explained more thoroughly for readers unfamiliar with these concepts. For instance, MVC architecture helps organize code by separating the application into three interconnected components, which can make it easier to manage and scale.
The information provided appears accurate and reliable, with no evident signs of fake news or misleading content. The article does not seem to follow any unethical practices, as it does not copy content from other sources without attribution. However, it primarily reiterates existing knowledge about Laravel rather than introducing new ideas or insights.
Overall, while the article provides valuable information about Laravel, it could enhance its contribution to the field by offering deeper insights or unique perspectives on the framework's capabilities.
Use of Evidence and References:
The article references various features and changes introduced in Laravel versions 6, 8, and 9, which are relevant to the discussion. However, it lacks citations or links to external sources that could further validate the claims made. The absence of references to official Laravel documentation or community discussions leaves a gap in the evidence supporting the article's assertions.
More robust evidence, such as user testimonials or performance comparisons with other frameworks, would strengthen the article's claims. Additionally, including links to relevant resources would allow readers to explore the topic further.
Further Research and References:
Further research could explore the following areas:
- The impact of Laravel on team productivity in real-world projects.
- Comparative studies of Laravel with other PHP frameworks in terms of performance and usability.
- Case studies of successful applications built with Laravel.
- The learning curve for new developers transitioning to Laravel from other frameworks.
Recommended sources for additional reading could include:
- The official Laravel documentation.
- Community forums and discussions on Laravel.
- Books or online courses focusing on Laravel development.
Questions for Further Research:
- What are the common challenges developers face when transitioning to Laravel from other frameworks?
- How does Laravel compare to other PHP frameworks in terms of performance and scalability?
- What are the best practices for optimizing Laravel applications for large-scale use?
- How does Laravel's community support contribute to its popularity and usability?
- What are the security features of Laravel, and how do they compare to those of other frameworks?
- How can developers effectively manage dependencies in Laravel applications?
- What role does Laravel play in the development of RESTful APIs?
- How does Laravel's use of Composer enhance its functionality?
- What are the implications of using Laravel in a microservices architecture?
- How do Laravel's features evolve in response to changes in web development trends?
Rate This Post
Rate The Educational Value
Rate The Ease of Understanding and Presentation
Interesting or Boring? Rate the Entertainment Value
Contributor's Box
Founder, lead software engineer, technical writer, and mentor at Boostlane.
I research ways to use artificial intelligence in information management and connect learners with mentors.
My ambition is to contribute to innovation and wealth creation by building a useful information-management platform, sharing knowledge, and helping people develop new skills.