Technologies

Laravel 7 - What's new in the next version of the framework?

Laravel 7,Framework,PHP,Development,Software House,Update
Laravel 7,Framework,PHP,Development,Software House,Update

Laravel 7 is now released, so let's take a look at the modifications that wait for us in this update. Due to the recent numbering change (since 6.0, September last year, Laravel uses Semantic Versioning) we immediately know that the new version has breaking changes, i.e. updates that change the framework's operation significantly.  Therefore, we will look at these changes, review new functionalities and check whether it is worth moving to the latest version. 


Laravel Airlock 


Laravel Airlock is another official package of Laravel, created by the creator of the framework, Taylor Otwell. It is an alternative to Laravel Passport, which we can use when we need to authenticate API users, but we don't need to use all OAuth2 functions. Examples of such applications include SPA (Single Page Application) or mobile applications. Until now, to deal with the identification and authorization of users querying our application via the API, we were forced to either write our own solutions or use the Passport package, which had all OAuth2 functionalities, which was often unnecessary and used only a fraction of its function. 


The programmable casting of attributes in Eloquent 


This allows us to define our own functions that cast attributes in the Eloquent model. Up to version 7, the only options we had were to cast onto basic PHP types, collections, and Carbon objects. We can currently define any method for casting attributes by implementing the CastsAttributes interface.

An example of implementation of the class:

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Json implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return array
     */
    public function get($model, $key, $value, $attributes)
    {
        return json_decode($value, true);
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  array  $value
     * @param  array  $attributes
     * @return string
     */
    public function set($model, $key, $value, $attributes)
    {
        return json_encode($value);
    }
}

  And an example of how to use it:

namespace App;

use App\Casts\Json;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'options' => Json::class,
    ];
}  

Blade components


 If you also use Vue in addition to Laravel during your work and (just like me) love the concept of components in it, you will love this feature. The system of components in Blade has been completely rebuilt. The old @component construction (which is the first breaking change in this version) has been replaced with a completely new one that resembles the one known from Vue. Components are simply classes in which we can implement any methods and decide which views to display. 

We will cover this feature in more detail in future articles, but for now, you can see what it looks likein the documentation.


 Http facade 


 To facilitate work with queries to external services in the new version of Laravel, the Illuminate \ Support \ Facades \ Http class appears, which is a simple wrapper around the GuzzleHttp package.

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders([
    'X-First' => 'foo'
    'X-Second' => 'bar'
])->post('http://test.com/users', [
    'name' => 'Taylor',
]);

return $response['id'];

  In addition to invoking queries, this facade also makes testing easier.

Http::fake([
    // Stub a JSON response for GitHub endpoints...
    'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),

    // Stub a string response for Google endpoints...
    'google.com/*' => Http::response('Hello World', 200, ['Headers']),

    // Stub a series of responses for Facebook endpoints...
    'facebook.com/*' => Http::sequence()
                            ->push('Hello World', 200)
                            ->push(['foo' => 'bar'], 200)
                            ->pushStatus(404),
]);
  

Easier string operations 


 To simplify the use of the Str :: helper, the Stringable class has been introduced, thanks to which we can perform string operations in a more object-oriented way. Due to this solution, instead of using the traditional approach, assigning function results to subsequent variables, we can call the function chain, making our code more readable.

return (string) Str::of('  Laravel Framework 6.x ')
                    ->trim()
                    ->replace('6.x', '7.x')
                    ->slug();
 

Changes in routing 


In the new Laravel version, the framework parts responsible for routing have been rewritten. Thanks to this, we have gained new possibilities and increased routing performance. One of the main news is the ability to define the name of the column on which the route model binding works. Until now, to use route binding after a key other than ID, we had to define for the whole model, so that the column was always used. After the latest changes it will be possible per route, which increases the flexibility of the solution.

Route::get('api/posts/{post:slug}', function (App\Post $post) {
    return $post;
});

  Another new feature is automatic relationship detection. If we use two models, in one route Laravel will try to find out if they are related by any relation and will allow to query only those models that are related to each other.

Route::get('api/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
    return $post;
});

  When rewriting some routing, caching has also been improved, thanks to which the application may work twice as fast in some situations. 


CORS support 


Until now, the API written in Laravel was associated with problems with Cross-Origin Resource Sharing. If our API was on a different domain than the application that consumed them, requests weren’t accepted. To deal with this problem, you had to use external packages. OPTIONS queries are now supported with every new Laravel installation. 



MySQL 8 support 


After a few years, we finally got the opportunity to use MySQL 8 with Laravel. The biggest advantage of this is that it will significantly improve the efficiency of working with the database. There is no doubt that current version is faster for reading and writing operations in a database  compared to version 5.7. If you want to know more details on the performance of both databases, I suggest you read this article. I like the removal of caching queries. Unfortunately, this mechanism most often caused more issues than benefits. In Laravel, we now have much more effective solutions that have been replacing this mechanism for a long time. 

 Of course, version 8 brings a lot of improvements and new possibilities. It is fairly robust solution for use in more demanding projects. From my point of view, the most interesting changes are the introduction of support for UUID and the Common Table Expressions (CTE) mechanism, which is present in PostgreSQL and MariaDB. With such features, the MySQL database is more efficient and allows you to create even more complex solutions based on it. If you want to know more about the new version of the database, then I refer you to this article.


  If you need experienced software house working in PHP

Write to us!

 
Piotr Nowak
Fullstack Developer, currently crazy about the Laravel + Vue stack, in his work, he particularly values the creation of modern, dedicated solutions. In moments of respite from the code turns into a lover of independent films.

What do you need?

Website

IT system

Mobile app

Graphic design

Technical support

Chatbot

The preferred form of contact

Please provide contact details

The personal data administrator is HighSolutions sp. z o.o. (hereinafter the "Company") with headquarters in Tarnowo Podgórne, ul. Szkolna 21/1, 62-080 Tarnowo Podgórne, e-mail adress kontakt@highsolutions.pl. Detailed information on the processing of personal data can be found in the privacy policy.

Thank you!

We will get back to you soon