What’s new in Laravel 8

Hello habr! On the eve of the start of the course “Framework Laravel”, our expert and part-time active member of the Russian Laravel community – Vitaly Yushkevich, prepared an overview of new products in Laravel 8. I give the floor to Vitaly:

Hello!

The latest release of Laravel 8 has been controversial. On the one hand, there are many new tools for a quick start; improved work of factories, given the folder structure in “as usual used” format. On the other hand, in this release, the approaches to basic web application development in Laravel were significantly changed, and the usual ui with support for bootstrap and react preset was added as a fix in a separate library after a lot of outrage from the community.

Let’s take a closer look at the changes and how they will change the laravel app development landscape in the future.


Let’s try to install the new version of Laravel and take a closer look at the new items.

Laravel app is installed using globally installed installer https://github.com/laravel/installer… If you already have it installed, you can change the dependency in your global composer.json. It is located along the following path:

~/.composer/composer.json. 

Current version for laravel 8:

"laravel/installer": "^4.0".

After saving the changes, run the command:

composer global update 

and after that the new version of the framework will be available.

When creating a new application, a new flag was added:

--jet             Installs the Laravel Jetstream scaffolding

Let’s talk about this tool separately, but for now let’s create a new application.

To install and work laravel 8 raised the requirements for the minimum php version to 7.3. All requirements can be viewed at the link https://laravel.com/docs/8.x/installation#server-requirements

Changes

Changing the structure of model directories

By popular demand from the community, all models are now placed in the Models directory with the appropriate namespace (App Models) by default.

At the same time, backward compatibility of the make: model command has been preserved. If you have a Models directory, then when you run the command php artisan make:model ModelName a new model will be automatically created in the Models directory with the appropriate namespace (App Models). If you don’t have this directory, then the model will be created in the root app and the namespace will be App. A trifle, but nice.

Migration squashing

Over time, the project is overgrown with a large number of migration files. This is not very convenient if you want to see your current schema, or if you have to do all the migrations frequently.

Laravel 8 introduces the schema: dump command, which dumps the current database into a separate schema directory. If you run this command with the -prune flag, all current migrations will be removed. With the next database updates, this dump will be performed first, and then the remaining migrations.

Model Factory Classes

In this release, the work with factories has been reworked. Model factory is a full-fledged class, and the factory is called by calling the model’s factory () method (* The model must use the HasFactory trait).

This greatly simplifies working with factories. For example, it is now much more convenient to specify different states for generating a model through separate methods and to consistently apply state chains when calling the make () or create () method. For instance,

User::factory()->active()->subscribed()->client()->make()

Improved work with links. There are 2 magic methods: has and for. For example, if we want to create a user with 5 posts, we can write:

User::factory()->has(Post::factory()->count(5))->create()
более "магичный" вариант тоже будет работать
User::factory()->hasPosts(5)->create()

The for () method works similarly for BelongsTo relationships

Improvements in Maintenance Mode

The php artisan down command has new flags:

--redirect[=REDIRECT]  The path that users should be redirected to
--render[=RENDER]      The view that should be prerendered for display during maintenance mode
--retry[=RETRY]        The number of seconds after which the request may be retried
--secret[=SECRET]      The secret phrase that may be used to bypass maintenance mode
--status[=STATUS]      The status code that should be used when returning the maintenance mode response [default: "503"]

If we set the secret parameter, like this:

php artisan down --secret=my_secret_down_key

then we can refer to the site at mysite.com/my_secret_down_keyand then work with the site as if it were in normal mode (a cookie is set). In this case, the application will be in maintenance mode for other users.

The render parameter allows the template to be rendered as final html code. This parameter can be used both to display a custom template (we set our template), and to use the rendering of the error pages (—render = “errors :: 503”). The latter use case is useful in the following – if you run composer update while updating the application, then your dependencies may break and the output of the standard stub will break. If you use render 503 pages, then the output will not break and the previously prepared html page template will be displayed.

Improved work with Closure-Based Event Listeners

Listeners for events can be declared through closures. This approach can be justified when you want to save money on creating separate classes (a controversial advantage, in my opinion, but there is a place to be).

The essence of the improvement is reduced to optimization:

Раньше нужно было писать так:
Event::listen(MyEvent::class, function(MyEvent $event) {
    // do smth
})

Теперь можно писать так:
Event::listen(function(MyEvent $event) {
    // do smth
})

Если нужно сделать обработкик queueable, то замыкание нужно обернуть в другое:
Event::listen(queueable(function(MyEvent $event) {
    // do smth
}))

Time Testing helper

A new class, Wormhole, has been added, which adds a number of methods for testing, allowing flexibility to change the “current date” from which we want to test. There is flexible support (positive and negative offsets, changes in different units – from milliseconds to years) for changes in the current time, as well as specifying the exact time.

Example from the documentation:

public function testTimeCanBeManipulated()
{
    // Travel into the future...
    $this->travel(5)->milliseconds();
    $this->travel(5)->seconds();
    $this->travel(5)->minutes();
    $this->travel(5)->hours();
    $this->travel(5)->days();
    $this->travel(5)->weeks();
    $this->travel(5)->years();

    // Travel into the past...
    $this->travel(-5)->hours();

    // Travel to an explicit time...
    $this->travelTo(now()->subHours(6));

    // Return back to the present time...
    $this->travelBack();
}

Improved rate-limit performance

In the previous version, the rate limit was set at the middleware level. Starting from version 8, rate limit control has been moved to RouteServiceProvider through closures. Flexibility has been greatly improved. Now, within one midleware, you can configure different rate limits, as well as set limits for users or by ip (for example, give privileged users less stringent restrictions).

JetStream and frontend changes

Along with this release, a new scaffolding product was released to replace the UI package, dynamic blade components. Perhaps this is one of the biggest changes in this release. However, it is also controversial. This package has quite large capabilities, we will consider it in detail in a separate article.

Job batching

A new batch () method was added to the Bus facade for processing task blocks. You can control whether the following methods run after all tasks have been completed. Sample code from the documentation:

use AppJobsProcessPodcast;
use AppPodcast;
use IlluminateBusBatch;
use IlluminateSupportFacadesBus;
use Throwable;

$batch = Bus::batch([
    new ProcessPodcast(Podcast::find(1)),
    new ProcessPodcast(Podcast::find(2)),
    new ProcessPodcast(Podcast::find(3)),
    new ProcessPodcast(Podcast::find(4)),
    new ProcessPodcast(Podcast::find(5)),
])->then(function (Batch $batch) {
    // All jobs completed successfully...
})->catch(function (Batch $batch, Throwable $e) {
    // First batch job failure detected...
})->finally(function (Batch $batch) {
    // The batch has finished executing...
})->dispatch();

return $batch->id;

Other changes

This release also adds a closure for job dispatch, improvements to artisan serve, updates to the Routing Namespace and bug fixes. Full changelog access in documentation. https://laravel.com/docs/8.x/releases and in the repository 🙂

Instead of totals

This release adds convenience to work and brings many improvements. However, it doesn’t feel like it was the strongest Laravel release. Changes in the frontend part caused a lot of discussions, “forcing” to add the old ui by fix through a separate library. Taylor has outlined a new vector for the development of the framework, with which many may disagree. Will Taylor keep this vector in the next release? Will laravel keep the same rate of attracting people to its community? Time will be the only judge.

That’s all. Using the link below you can sign up for a free webinar, in which we will tell you in detail about the course program and the learning process, as well as answer your questions.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *