Laravel

What’s new in Laravel 7.0

It’s a boom in the PHP market when everyone gets to know that Laravel 7 is launched.

So, let’s take a look at which year which version is launched.

VersionReleaseBug Fixes UntilSecurity Fixes Until
7 March 3rd, 2020 September 3rd, 2020 March 3rd, 2021
6 (LTS) September 3rd, 2019 September 3rd, 2021 September 3rd, 2022
5.8 February 26th, 2019 August 26th, 2019 February 26th, 2020
5.7 September 4th, 2018 March 4th, 2019 September 4th, 2019
5.6 February 7th, 2018 August 7th, 2018 February 7th, 2019
5.5 (LTS) August 30th, 2017 August 30th, 2019 August 30th, 2020

Where LTS stands for LONG TERM SUPPORT

Let’s look at the featured launched in laravel 7.0

Laravel Airlock

So this feature was built by Taylor Otwell. At a high level here are some of the highlight features:

  • Secure SPA Authentication with CSRF protection
  • API tokens
  • API token abilities (i.e., scopes)
  • Mobile application authentication.
  • Token revocation

Want to know more about Laravel airlock please visit airlock documentation

Custom Eloquent Casts

Laravel has a variety of built-in, helpful cast types; but sometimes, it needs to define your own cast types. You may now accomplish this by defining a class that implements the CastsAttributes interface.

Classes that implement this interface must define a get and set methods. The get method is responsible for transforming a raw value from the database into a cast value, while the set method should transform a cast value into a raw value that can be stored in the database. As an example, we will re-implement the built-in json cast type as a custom cast type:

Below is the example showing basic use of custom eloquent Casts

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class YourClassName 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);
    }
}

Okay if you defined a custom cast type, then we can attach it to our model attribute.

<?php

namespace App;

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

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

Blade Component Tags & Improvements

All public properties and methods defined on the component class will automatically be made available to the component view. Any additional HTML attributes specified on the component may be managed using the automatically included $attribute variable, which is an attribute bag instance. Blade components have been overhauled to allow tag-based rendering, attribute management, component classes, inline view components, and more. Since the overhaul of Blade components is so extensive, please consult the full Blade component documentation to learn about this feature.

HTTP Client

Laravel now provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel’s wrapper around Guzzle is focused on its most common use cases and wonderful developer experience. 

Below example shows HTTP Client example in Laravel

First of all, we have to install Guzzle HTTP client.

 composer require guzzlehttp/guzzle 

GET Request:

public function getGuzzleRequest()
{
    $client = new \GuzzleHttp\Client();
    $request = $client->get('http://myexample.com');
    $response = $request->getBody();
   
    dd($response);
}

Post Request:

public function postGuzzleRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://myexample.com/api/posts";
   
    $myBody['name'] = "Demo";
    $request = $client->post($url,  ['body'=>$myBody]);
    $response = $request->send();
  
    dd($response);
}

PUT Request:

public function putGuzzleRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://myexample.com/api/posts/1";
    $myBody['name'] = "Demo";
    $request = $client->put($url,  ['body'=>$myBody]);
    $response = $request->send();
   
    dd($response);
}

DELETE Request:

public function deleteGuzzleRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://myexample.com/api/posts/1";
    $request = $client->delete($url);
    $response = $request->send();
  
    dd($response);
}

Fluent String Operations

You are likely familiar with Laravel’s existing Illuminate\Support\Str class, which provides a variety of helpful string manipulation functions. Laravel 7 now offers a more object-oriented, fluent string manipulation library built on top of these functions. You may create a fluent Illuminate\Support\Stringable object using the Str::of method. A variety of methods may then be chained onto the object to manipulate the string:

See the below example for more clarification

$title = "thanks for visiting us"
return (string) Str::of($title)
                    ->plural()
                    ->kebab()
                    ->ucfirst();

Want to know about more cases that are used in programming languages click on the link.

Route Model Binding Improvements

Now Laravel7 is having route model binding improvement

when implicitly binding multiple Eloquent models in a single route definition, you may wish to scope the second Eloquent model such that it must be a child of the first Eloquent model.

Laravel 7 will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent

See the below example, how we can use it in our program

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

Multiple Mail Drivers

Laravel 7 allows the configuration of multiple “mailers” for a single application. Each mailer configured within the mail configuration file may have its own options and even its own unique “transport”, allowing your application to use different email services to send certain email messages. For example, your application might use Postmark to send transactional mail while using Amazon SES to send bulk mail.

Route Caching Speed Improvements

Laravel 7 includes a new method of matching compiled, cached routes that have been cached using the route:cache Artisan command. On large applications (for example, applications with 800 or more routes), these improvements can result in a 2x speed improvement in requests per second on a simple “Hello World” benchmark. No changes to your application are required.

CORS Support

Laravel 7 includes first-party support for configuring Cross-Origin Resource Sharing (CORS) OPTIONS request responses by integrating the popular Laravel CORS package written by Barry vd. Heuvel. A new cors configuration is included in the default Laravel application skeleton.

Query Time Casts

Sometimes you may need to apply casts while executing a query, such as when selecting a raw value from a table. For example, consider the following query:

use App\Post;
use App\User;

$users = User::select([
    'users.*',
    'last_posted_at' => Post::selectRaw('MAX(created_at)')
            ->whereColumn('user_id', 'users.id')
])->get();

The last_posted_at attribute on the results of this query will be a raw string. It would be convenient if we could apply a date cast to this attribute when executing the query. To accomplish this, we may use the withCasts method provided by Laravel 7:

$users = User::select([
    'users.*',
    'last_posted_at' => Post::selectRaw('MAX(created_at)')
            ->whereColumn('user_id', 'users.id')
])->withCasts([
    'last_posted_at' => 'date'
])->get();

MySQL 8+ Database Queue Improvements

In previous releases of Laravel, the database the queue was not considered robust enough for production usage, due to deadlocks. However, Laravel 7 provides improvements to applications using MySQL 8+ as their database-backed queue. By using the FOR UPDATE SKIP LOCKED clause and other SQL enhancements, the database driver may now safely be used in higher volume production applications.

Artisan test Command

In addition to the phpunit command, you may now use the test Artisan command to run your tests. The Artisan test runner provides beautiful console UX and more information regarding the test that is currently running. In addition, the runner will automatically stop on the first test failure:

Markdown Mail Template Improvements

The default Markdown mail template has received a fresh, more modern design based on the Tailwind CSS color palette. Of course, this template can be published and customized according to your application’s needs:

Related Articles

Leave a Reply

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

Back to top button