The code behind Laravel 6

Coding (Php 7.x)

Sep 4, 2019

An intensive explanation about what's new on the new version of our favourite PHP Framework
 
/img/blog/the-code-behind-laravel-6.jpg

Warning the content below contains beautiful code!
If you have a heart condition or prefer procedural code.
Do not trespass this paragraph

 

I do not know if it's only me but every time there is a big update or a new release of some stuff that I use I get exited like it is Christmas boxing day.

 

Sometimes these are small updates whereas other times these updates can be quite huge and really important.

 

In this case the update is huge.

 

Why is that?

 

In this post, we will review all the new features and the state of art of the next release of Laravel.

 

Laravel in its 6.0 version

 

But let’s start from the beginning.

 


What is laravel?

 

Laravel is a PHP framework, it is a system of files and components nicely put together that allows web developers that use it to work faster, and with much more handy functionalities.
 

I have actually already reviewed Laravel and other frameworks in a series of blog post several months ago so I will not delve into it.

 

The series has descriptions, news, and interview of the authors and I believe it is the most accurate series about PHP Frameworks online at the moment.


But now, let’s talk about Laravel.

 

What so special about it and why there are thousands of projects that use it?

 

Laravel is one of the best PHP frameworks of all time,

 

surely it one of the best marketed around.

 

It is very easy to use and it includes features such as Thinker an amazing REPL. Eloquent personally the best ORM I have ever tried, then we have Nova, Forge, Mix, Valet, and plenty more, really plenty.

 

Just to illustrate the importance of Laravel there are vacancies in job boards that ask specifically for ‘Laravel Developer’ not ever PHP developer anymore.

 

It has really changed the game and definitely for the better.

 

Alright, Laravel is cool but, why doing a post now about it?

 

The reason is that Laravel 6.0 has been officially released September the 3rd.

 

It has several amazing feature that I want you to discover.

 

What is new in Laravel 6.0?

 

As a tradition, releases of this PHP framework have been published every six months (the months are generally February and August), often these releases contain breaking changes and you need to pay a lot of attention when updating from an older version to a newer, even though this is not always the case.

 

At the same time, minor releases and other little patches are published on the variable time span, they can go from a couple of days to several weeks.

 

Since there are a lot of contributors that update it on a daily basis the master version is usually updated very frequently.

 

Despite the upcoming version is a major release it does not contain any major breaking features.

 

If you think that Laravel 5 was released on February 2015 this is quite an achievement

 

Taylor Otwell, the mind behind all of this explained that the reason for that is that now, this PHP framework, is mature enough and its bones do not need to be extremely twisted in order to improve the quality of the code.

 

Laravel 6 will be an LTS version the previous one where 5.5 and previously 5.1.

 

The difference between a general release and an LTS one is the bug and security fixes are going to be provided per respectively 2 and 3 years.

 

This is the longest support period up to date.

 

In comparison, the support for the other version is only 6 months and 12 months.

 

To be clear with the dates eventual bugs are going to be fixed until September 3rd, 2021 and the security problem are going to be fixed until September 3rd, 2022.

 

Unlike the other major releases, Laravel 6.0 does not have any big changes to the file system, in fact, it just improves the work done in Laravel 5.8.

 

It contains, though, several important improvement

 

Let’s have a look at them in details.

 

 

Discover Semantic Versioning

 

To be in sync with the other parties of the environment (all the packages available) from now on the main product, Laravel (laravel/framework) will follow the semantic versioning standard.

 

It is a versioning system that tries to solve the problem that software developers have when releasing a new feature on an existing codebase.

 

It is a standard method that allows keeping track of the new commits and the development process of the software itself.

 

It simply consists of 3 numbers separated by a dot.

 

The format is 1.2.3

 

The first number represents a major version. The second or middle number stands for a minor version release while the third and last number is used to show patch fixing

 

This new system of showing releases does not change the cycle in fact it will stay the same.

 

If you want to read more about semantic versioning here is a summary

 


Laravel Vapor

 

 

Let step back for a second and do a bit of explanation, 

 

we all know what a server is.

 

I am sure we all know what a serverside language is.

 

Any scripts whether in PHP, NodeJs, Java etc need a server to run properly.

 

A trend visible during the last couple of years is to run scripts in serverless mode.

 

Of course, you will still have a server but now the script is not depended on the programming language anymore.

 

AWS Lambda is one of the most famous services that allows us to use serverless.

 

It did not support PHP for a long time, you can actually use it by leverage SDK but still, using it is somehow a pain in the butt.

 

Here come Mr Otwell and his new creation Laravel Vapor.

 

Vapor is a serverless platform for Laravel application.

 

At the moment, the majority of web developer used Laravel Forge to provision and deploy their apps. 


Forge allows you to connect your server and Forge would provision it specifically for your Laravel application. 

 

Laravel Vapor does more than this. 


you do not have to bother about scaling as it is going to be automatically done for you.
 

It allows any web developer that sign in to the service to scale on-demand and without any server maintenance.

 

It manages several services such as CloudFront, queues, Redis, databases and cache memory as well.

 

 

Improved Authorization Responses

 

Authorization has always been an important topic for PHP developers,

 

Being able to use sessions is an incredible advantage for any PHP developers, 

 

The responsible for this feature is Gary Green a web developer based in London,

 

On of the problem of the previous version of Laravel was the difficulty to get and show authorization message depending on the different users logged.

 

In Laravel 6.0 this is change thanks to Gate class, 

 

The one you see below it the inspect method of this class:

 

public function inspect($ability, $arguments = [])
{
    try {
        $result = $this->raw($ability, $arguments);
        if ($result instanceof Response) {
            return $result;
        }
        return $result ? Response::allow() : Response::deny();
    } catch (AuthorizationException $e) {
        return $e->toResponse();
    }
}

 

The value returned from this method is an instance of the Response class, which means you can now do this in your code:

 

$response = Gate::inspect('edit', $record);

if ($response->allowed()) {
    // User is authorized to edit the record...
}

if ($response->denied()) {
    echo $response->message();
}

 

These messages are now returned to the view when we use the method authorize() in a Controller (or Router)

 

 

Job Middleware

 

Middleware are amazing pieces of code that filter requests before they enter your application,

 

One of the reasons Laravel became famous during the recent past is because of the smart use of a lot of them.

 

It has the authorization middleware, a CSRF one, encryptCookies, one that trims the strings plus the possibility to add new ones.

 

Now, with Laravel 6 we have the possibility to create custom-made job-specific middlewares for queued jobs that are going to save a lot of our developer time and make better code by wrapping logic around the execution of jobs.

 

Then, after the job has been created we can simply access the middleware by calling the method middleware() and return the class we want to instantiate.

Let's see an example:

// This is the handle method in one of our job class in ThrottledJob.php
public function handle() {
    Redis::throttle('forge_api')->allow(30)->every(60)->then(function () {
        // perform 1 api call
    }, function () {
        return $this->release();
    });
}

// Code of the previous method now extracted into a specific middleware
class TrottleForgeApi {
    // Process the queued job.
    public function handle($job, $next) {
        Redis::throttle('forge_api')
             ->allow(30)->every(60)
             ->then(function () use ($job, $next) {
                 // perform 1 api call
                 $next($job);
              }, function () use ($job) {
                 $job->release();
              });
    }
}


// middleware attached to the job (it will run through the middleware before processing)
public function middleware()
{
    return [new TrottleForgeApi];
}

 


Lazy Collections


In one of the most popular episodes of Laracasts the website in which you can find hundreds of hours of tutorials for Laravel and PHP, Jeffrey Way describes collections as arrays with steroids, and I found this sentence quite fascinating.

 

I also love arrays and their hundreds of functions.

 

The reality is the collections were already incredibly powerful tools and there was really little space for improvement here.

 

The new version of Laravel leverages one of the less popular yet sturdy features of PHP:

 

Generators.

 

Generators are an amazing feature that allows you to work and manage huge set of data and keep the memory at the minimum level because the value of the cursor is not loaded all at once but a bit at a time.

 

Here is what I mean:

 

Let follow one of the examples of the official documentation:

 

$users = App\User::cursor()->filter(function ($user) {
    return $user->id > 500;
});

foreach ($users as $user) {
    echo $user->id;
}

 

What you see here is an example of method chaining, in order to work properly the filter() method requires the variable returned by the cursor() method.

 

cursor() returns a variable of type LazyCollection (That nothing other than the class Illuminate\Support\LazyCollection),

 

As said this method invokes the LazyCollection::make() method that uses PHP generators.

 

Thus, load element one at a time, in this case, you can even filter through 100000 element in your code they will be loaded and executed only at due time.

 

 

Eloquent Subquery Enhancements

 

If you have been using PHP or a PHP framework for a while you know how dangerous or effective can be a query to the database in your script.

 

If the query is not written properly the performance of our application drop and the effect compound for each new query.

 

A way to solve this problem when working with a database is trying to write the less possible amount of query and use subqueries when there are multiple requests combined.

 

Jonathan Reinink, helped hugely during the working phase of this release implementing several enhancements to the query builder on the select() method, the orderBy() subquery, and the from() subquery.

 

In the video below the author explains what he did and how we can use this new feature in our next Laravel 6 application.

 

 

Laravel UI

 

One choice that surprised me about Laravel 6 was to remove the initial scaffolding of everything regarding the front-end.

 

Laravel 5 it famous to have brought VueJS to footlights, a Tweet from Taylor Otwell about this Javascript Framework and the You’s repository started to be forked and starred like there was no tomorrow.

 

With this new version though, both Bootstrap and VueJs have been extracted and a standalone Compores package made from them.

 

The most probable of the reasons is that, if on the one hand it is not confirmed that all Laravel developers use these two frontend frameworks for their applications, at the same time it is sure that everyone can benefit from the reduction for files and size and therefore increase in the speed of the new system.

 

Anyway, do not worry, if there is your framework of choice and you also want to use the command make:auth you only need to include laravel/ui to your application.

 

Here is how:

 

composer require laravel/ui
php artisan ui vue --auth

 

By default, both these packages will be installed using NPM.

 

Once the package is installed you can choose which Javascript framework you want to use by typing 

 

php artisan ui vue
php artisan ui vue --auth

// Or 
php artisan ui react
php artisan ui react --auth


Upgrading from 5.8 to 6.0

Even this upgrade guide of Laravel uses the same style.

 

The method they have used has been to divide and order the changes by the level of impact they are going to have to your current application.

 

In the case of upgrading from Laravel 5.8 to this new version, there are only 2 hight-impact changes that can break your application.

 

 
Authorized Resources & viewAny

If you are using the method authorizeResource() to attach authorization policies to controller you mush now define a vewAny() method,

 

It should have to be called during access to the index method by the user.

 

Under other conditions invoking the index method will be considered unauthorized.

 

String & Array Helpers

As we have seen with the frontend scaffolding one goal of this new version is to keep the framework leaner and focused on one thing alone.

 

For this reason, several features have been extracted and make a standalone package that we can use if we want.

 

Those two helpers are not an exception.

 

You can call their helpers to use Illuminate\Support\Str and Illuminate\Support\Arr classes

 

Otherwise, you can add the package using the command below:

 

Conclusion

 

In a world of tech that includes constant changing and in which a 6 months software is considered ancient if not dangerous Laravel stands as one of the PHP frameworks that is here to stay.

 

Its beautiful code, branding, and easy-to-use make this framework one of the most popular.

 

Seriously, have you seen its documentation?


Not to mention the whole ecosystem that already includes top of the notch products such as Forge, Lumen, Valet, Cashier, Nova and Tinker and still increases in the number and in quality every couple of months. 

 

Last arrived in the family the serverless platform Vapor.

 

We can only expect great things from Otwell and its team.

 

I am excited to try it on some new projects and I would also like to know what are your thought on this new product. 
 

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Php 7.x) Aug 19, 2019

Good Practices: how to sanitize, validate and escape in PHP [3 methods]

See details
Coding (Php 7.x) Sep 12, 2019

Good Practices: PHP Security, How to manage password

See details
Coding (Php 7.x) Sep 19, 2019

Good Practices: handling error and exceptions in php

See details
Get my free books' review to improve your skill now!
I don't want to improve