Laravel 8 New Features

Solomon Eseme - Dec 16 '20 - - Dev Community

Laravel 8 is here with amazing new features to better improve our development processes with the framework.

On September 6th, 2020, Laravel released the new version of Laravel shipped with lots of improvements, optimization, and the introduction of Laravel JetStream.

In this article, we will look at what is new in Laravel 8 and Laravel 8 new features and how to get started with each of them in your new project.

We will work through the current state of the framework and give you some tips and foundational knowledge to help you start using Laravel 8.

We’ll cover the following:

  1. Introduction to JetStream
  2. Model Factory Classes
  3. Model Directory
  4. Migration Squashing
  5. Job Batching and Queue Improvements
  6. Improved Rate Limiting
  7. Maintenance Improvements
  8. Dynamic Blade Components
  9. Tailwind Pagination Views
  10. Time Testing Helpers
  11. Improvements to artisan serve
  12. Event Listener Improvements

Let’s get started:

Before we delve in, if you’re a backend developer or looking at delving into this career path, join other developers to receive daily articles on backend development that will boost your productivity.

Join our Community

What is new in Laravel 8

Introduction to JetStream

JetStream is one of the main feature added to the Laravel 8 new features

JetStream is an application scaffolding for Laravel that provides a basic setup for any project including the famous Laravel Auth for Login, two-factor authentication, registration, email verification, etc.

It also provides API support through Laravel Sanctum.

Laravel JetStream is more like an improved version of the legacy Laravel Authentication process and UI.

Getting Started with JetStream

Let’s look at how to install and use JetStream in our project.

Installation

Installing via composer:

composer require laravel/jetstream
Enter fullscreen mode Exit fullscreen mode

Install Jetstream With Livewire

php artisan jetstream:install livewire
Enter fullscreen mode Exit fullscreen mode

Or, Install Jetstream With Inertia

php artisan jetstream:install inertia
Enter fullscreen mode Exit fullscreen mode

The inertia and livewire are just different views components that come with JetStream, you can read more about Inertia and Livewire.

You can also go through the installation process from the official documentation to understand even more.

Finalizing Installation

After installing the package and the UI component of your choice, you can finalize the installation by running the commands below.

npm install && npm run dev 

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Model Factory Classes

In Laravel 8, the model factories have been completed rewritten as class-based and also improved to have first-class relationship support.

The newly introduced HasFactory trait is very helpful and we can now access different model methods like:

use App\Models\User; 

User::factory()->count(50)->create();
Enter fullscreen mode Exit fullscreen mode

For example, your User model might have an activated state that modifies one of its default attribute values.

You may define your state transformations using the base factory’s state method.

You may name your state method anything you like. After all, it’s just a typical PHP method:

/**

* Indicate that the user is activated.

*

* @return \Illuminate\Database\Eloquent\Factories\Factory

*/

public function activated()

{

return $this->state([

'account_status' => 'activated',

]);

}
Enter fullscreen mode Exit fullscreen mode

After defining the state transformation method, we may use it like so:

use App\Models\User; 

User::factory()->count(5)->activated()->create();
Enter fullscreen mode Exit fullscreen mode

You can learn more about model factory classes here.

Model Directory

The Laravel team has finally honored the request of developers around the world by introducing a new home for models.

What this means is that by default Laravel Models will now be placed inside app/Models folder and every setup are done by default for Laravel to honor this new directory.

Also, note that if the Models directory is not found, Laravel will default to use the previous apps folder as the home for models.

Migration Squashing

Have you ever build a Laravel project that has more than a hundred migration files and noticed how boated the migration folder becomes?

Well, Laravel 8 introduces Migration Squashing which will simply “Squash” or convert the migrations into a single file and save up hundreds of files in a folder.

To get started, simply run the following commands if your project is already running into numerous migrations.

php artisan schema:dump 

// Dump the current database schema and prune all existing migrations... 

php artisan schema:dump --prune
Enter fullscreen mode Exit fullscreen mode

What these commands will do is to generate a Schema file inside database/schema directory housing all your migrations.

When you create new migrations and run the php artisan migrate command, Laravel will execute the Schema file first before running any other migrations that are not part of the migration squash.

Interesting isn’t it 🙂

Job Batching and Queue Improvements

I have been looking at ways I can execute many jobs at once and still perform some actions at different stages of the process.

Well, Laravel 8 just introduced exactly what I have been looking for.

With the new Job Batching feature, I can execute multiple jobs and perform actions on completion.

Let’s look at how it works:

use App\Jobs\SendPost;

use App\Podcast;

use Illuminate\Bus\Batch;

use Illuminate\Support\Facades\Bus;

use Throwable;

$batch = Bus::batch([

   new SendPost(Post::find(1)),

   new SendPost(Post::find(2)),

   new SendPost(Post::find(3)),

   new SendPost(Post::find(4)),

   new SendPost(Post::find(5)),

])->then(function (Batch $batch) {

   // All jobs completed successfully...

   $this->emailAdminOnCompletion();

})->catch(function (Batch $batch, Throwable $e) {

   // First batch job failure detected...

   $this->emailAdminOnAnyError();

})->finally(function (Batch $batch) {

   // The batch has finished executing...

   $this->emailAdminOnDone();

})->dispatch();
Enter fullscreen mode Exit fullscreen mode

Looking at the script above, with the new batch method of the Job class, I sent out 5 different Post at the same time and still perform different actions at different stages of the Job.

With the introduction of the new methods, a lot of improvements have been made to the Queue class, you can read more about it.

Improved Rate Limiting

If all you do mostly with Laravel is write APIs like me, you might have had a hard time with Rate Limiting for your API middleware.

Laravel 8 comes with an improved Rate Limiting feature which is more flexible and easy to use with your API middleware.

Laravel comes with the RateLimiter facade which comes with lots of useful methods.

Let’s take a look at it:

use Illuminate\Cache\RateLimiting\Limit; 
use Illuminate\Support\Facades\RateLimiter; 

RateLimiter::for('global', function (Request $request) { 
   return Limit::perMinute(1000); 
});
Enter fullscreen mode Exit fullscreen mode

The for method accepts a rate limiter name and a closure that returns the limit configuration that should apply to routes that are assigned this rate limiter.

RateLimiter::for('uploads', function (Request $request) { 
   return $request->user()->admin() 
     ? Limit::none() 
     : Limit::perMinute(100); 
});
Enter fullscreen mode Exit fullscreen mode

You can build rate-limiting dynamically based on the incoming requests or authenticated user as shown above.

There are lots you could do with RateLimiter, take a look at them here.

Take a break and join other backend developers to receive our Laravel tips to boost your productivity.

Join our Community

Maintenance Improvements

Using php artisan down command to activate maintenance mode and set up "Allow IPs" is no longer supported.

Instead of using IPs, Laravel 8 introduces secret token-based access.

You simply generate a token when turning on maintenance mode and anyone with the token can still access the web pages.

Let’s see how:

// Turning on maintenance 

php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"
Enter fullscreen mode Exit fullscreen mode

Accessing the web pages in maintenance mode.

[https://masteringbackend.com/1630542a-246b-4b66-afa1-dd72a4c43515](https://masteringbackend.com/1630542a-246b-4b66-afa1-dd72a4c43515)
Enter fullscreen mode Exit fullscreen mode

How sweet 🙂 more on it here.

Dynamic Blade Components

Have you ever tried to render a component at runtime, well in a situation like this, Laravel introduces the dynamic-component component for just that?

This component will be rendered based on the values or variable passed at runtime.

Laravel also introduces lots of cool new blade components you can simply reuse in your project with just a simple artisan command instead of creating from scratch.

You can explore all of it here.

Tailwind Pagination Views

Sad news for Bootstrap fans.

Tailwind CSS is now the default style for Laravel 8 pagination.

The main reason for choosing Tailwind is because of how highly customizable, a low-level CSS framework gives you all the building blocks you need to build designs.

The good news for Bootstrap fans is that Bootstrap 3 and 4 views are still available, you only have to switch.

Time Testing Helpers

Every developer has a thing about TDD or Testing generally.

Like how will you be writing Code to Test your Code 🙂

Anyways, Laravel tends to improve an important aspect of Testing with Date and Times.

When writing test cases that involve the use of times and dates, Laravel 8 introduces new DateTime helpers in Laravel’s Test suite.

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();

}
Enter fullscreen mode Exit fullscreen mode

You can use the above methods to manipulate the current time while writing your tests in Laravel.

Happy Testing 🙂

Improvements to Artisan Serve

Our famous artisan serve command has received some improvements in this version.

Let’s look at what it is:

The Artisan serve command has been improved to include hot reloading even when an environment variable change has been detected in your .env file.

Event Listener Improvements

Laravel now supports closure based event listeners.

And can be registered by only passing the closure to the Event::listen method.

use App\Events\SendPost; 
use Illuminate\Support\Facades\Event; 

Event::listen(function (SendPost $event) { // });
Enter fullscreen mode Exit fullscreen mode

You can also mark the Closure based listener as queueable like so:

use App\Events\SendPost; 
use function Illuminate\Events\queueable; 
use Illuminate\Support\Facades\Event; 

Event::listen(queueable(function (SendPost $event) { // }));
Enter fullscreen mode Exit fullscreen mode

You can also customize it using these different methods below like other jobs:

Event::listen(queueable(function (SendPost $event) {

//

})->onConnection('redis')->onQueue('posts')->delay(now()->addSeconds(10)));
Enter fullscreen mode Exit fullscreen mode

Final thoughts

Laravel 8 is out and parked with all these amazing new features, you should try it out now.

We have also discussed in detail what is new in Laravel 8 and Laravel 8 new features.

Of course, there’re breaking changes, support policy, and semantic versioning, you might want to take a look at all here.

Originally published at https://masteringbackend.com on December 9, 2020.


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .