Laravel

Laravel-Difference between laravel 6 and laravel 8

In this blog, we will learn about the difference between laravel 6 and laravel 8 we will discuss the features which are introduced in laravel 8 but not available in laravel 6.

Difference Between Laravel 6 and Laravel 8, after the difference I will each point briefly.

LARAVEL 8LARAVEL 6
app/Models Directory changeLaravel Vapor Compatibility
New Landing PageImproved Exceptions Via Ignition
Controllers Routing NamespacingImproved Authorization Responses
Route CachingJob Middleware
Attributes on Extended Blade ComponentsLazy Collections
Better Syntax for Event ListeningEloquent Subquery Enhancements
Queueable Anonymous Event ListenersLaravel UI
Maintenance ModeSemantic Versioning
Closure Dispatch “Catch”
Exponential Backoff Strategy

Let’s start talking with what are features are introduced in Laravel 6, below data are taken from laravel official website, for more information click here

Semantic Versioning

The Laravel framework (laravel/framework) package now follows the semantic versioning standard. This makes the framework consistent with the other first-party Laravel packages which already followed this versioning standard.

Laravel Vapor Compatibility

Laravel 6 provides compatibility with Laravel Vapor, an auto-scaling serverless deployment platform for Laravel. Vapor abstracts the complexity of managing Laravel applications on AWS Lambda, as well as interfacing those applications with SQS queues, databases, Redis clusters, networks, CloudFront CDN, and more.

Improved Exceptions Via Ignition

Laravel 6 ships with Ignition, a new open-source exception detail page created by Freek Van der Herten and Marcel Pociot. Ignition offers many benefits over previous releases, such as improved Blade error file and line number handling, runnable solutions for common problems, code editing, exception sharing, and an improved UX.

Improved Authorization Responses

In previous releases of Laravel, it was difficult to retrieve and expose custom authorization messages to end-users. This made it difficult to explain to end-users exactly why a particular request was denied.

With the below example I try to elaborate on this feature.

/**
 * Determine if the user can view the given flight.
 *
 * @param  \App\User  $user
 * @param  \App\Flight  $flight
 * @return mixed
 */
public function view(User $user, Flight $flight)
{
    return $this->deny('Explanation of denial.');
}

The authorization policy’s response and message may be easily retrieved using the Gate::inspect method:

$response = Gate::inspect('view', $flight);

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

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

In addition, these custom messages will automatically be returned to your frontend when using helper methods such as $this->authorize or Gate::authorize from your routes or controllers.

Job Middleware

Job middleware allow you to wrap custom logic around the execution of queued jobs, reducing boilerplate in the jobs themselves. For example, in previous releases of Laravel, you may have wrapped the logic of a job’s handle method within a rate-limited callback:

/**
 * Execute the job.
 *
 * @return void
 */
public function handle()
{
    Redis::throttle('key')->block(0)->allow(1)->every(5)->then(function () {
        info('Lock obtained...');

        // Handle job...
    }, function () {
        // Could not obtain lock...

        return $this->release(5);
    });
}

In Laravel 6, this logic may be extracted into a job middleware, allowing you to keep your job’s handle method free of any rate-limiting responsibilities:

<?php

namespace App\Jobs\Middleware;

use Illuminate\Support\Facades\Redis;

class RateLimited
{
    /**
     * Process the queued job.
     *
     * @param  mixed  $job
     * @param  callable  $next
     * @return mixed
     */
    public function handle($job, $next)
    {
        Redis::throttle('key')
                ->block(0)->allow(1)->every(5)
                ->then(function () use ($job, $next) {
                    // Lock obtained...

                    $next($job);
                }, function () use ($job) {
                    // Could not obtain lock...

                    $job->release(5);
                });
    }
}

After creating middleware, they may be attached to a job by returning them from the job’s middleware method:

use App\Jobs\Middleware\RateLimited;

/**
 * Get the middleware the job should pass through.
 *
 * @return array
 */
public function middleware()
{
    return [new RateLimited];
}

Lazy Collections

Many developers already enjoy Laravel’s powerful Collection methods. To supplement the already powerful Collection class, Laravel 6 introduces a LazyCollection, which leverages PHP’s generators to allow you to work with very large datasets while keeping memory usage low.

For example, imagine your application needs to process a multi-gigabyte log file while taking advantage of Laravel’s collection methods to parse the logs. Instead of reading the entire file into memory at once, lazy collections may be used to keep only a small part of the file in memory at a given time:

use App\LogEntry;
use Illuminate\Support\LazyCollection;

LazyCollection::make(function () {
    $handle = fopen('log.txt', 'r');

    while (($line = fgets($handle)) !== false) {
        yield $line;
    }
})
->chunk(4)
->map(function ($lines) {
    return LogEntry::fromLines($lines);
})
->each(function (LogEntry $logEntry) {
    // Process the log entry...
});

Or, imagine you need to iterate through 10,000 Eloquent models. When using traditional Laravel collections, all 10,000 Eloquent models must be loaded into memory at the same time:

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

However, beginning in Laravel 6, the query builder’s cursor method has been updated to return a LazyCollection instance. This allows you to still only run a single query against the database but also only keep one Eloquent model loaded in memory at a time. In this example, the filter callback is not executed until we actually iterate over each user individually, allowing for a drastic reduction in memory usage:

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

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

Eloquent Subquery Enhancements

Laravel 6 introduces several new enhancements and improvements to database subquery support. For example, let’s imagine that we have a table of flight destinations and a table of flights to destinations. The flights table contains an arrived_at column which indicates when the flight arrived at the destination.

Using the new subquery select functionality in Laravel 6, we can select all of the destinations and the name of the flight that most recently arrived at that destination using a single query:

return Destination::addSelect(['last_flight' => Flight::select('name')
    ->whereColumn('destination_id', 'destinations.id')
    ->orderBy('arrived_at', 'desc')
    ->limit(1)
])->get();

In addition, we can use new subquery features added to the query builder’s orderBy function to sort all destinations based on when the last flight arrived at that destination. Again, this may be done while executing a single query against the database:

return Destination::orderByDesc(
    Flight::select('arrived_at')
        ->whereColumn('destination_id', 'destinations.id')
        ->orderBy('arrived_at', 'desc')
        ->limit(1)
)->get();

Laravel UI

The frontend scaffolding typically provided with previous releases of Laravel has been extracted into a laravel/ui Composer package. This allows the first-party UI scaffolding to be developed and versioned separately from the primary framework. As a result of this change, no Bootstrap or Vue code is present in default framework scaffolding, and the make:auth command has been extracted from the framework as well.

In order to restore the traditional Vue / Bootstrap scaffolding present in previous releases of Laravel, you may install the laravel/ui package and use the ui Artisan command to install the frontend scaffolding:

composer require laravel/ui "^1.0" --dev

php artisan ui vue --auth

Now we will Discuss about Laravel 8 Features

1 . app/Models Directory

-> The artisan:make model command will create the model in the app/Models directory.

2. New Landing Page

-> Laravel 8 comes with a new landing page for a brand new install. It is now redesigned and It is built using TailwindCSS, includes light and dark-mode capabilities, and by default extends links to SaaS products and community sites.

3. Controllers Routing Namespacing

-> No more double prefix issues! In previous versions of Laravel, the RouteServiceProvider had an attribute called namespace that was used to prefix the controllers in the routes files. That created a problem when you were trying to use a callable syntax on your controllers, causing Laravel to mistakenly double prefix it for you. This attribute was removed and now you can import and use it without the issue.

controllers routing namespacing

4. Route Caching

-> Laravel uses route caching to compile your routes in a PHP array that is more efficient to deal with. In Laravel 8, it’s possible to use this feature even if you have closures as actions to your routes. This should extend the usage of route caching for improved performance.

Route Caching

5. Attributes on Extended Blade Components

-> In Laravel 7 the child components didn’t have access to the $attributes passed to it. In Laravel 8 these components were enhanced and it is now possible to merge nested component attributes. This makes it easier to create extended components.

Attributes on Extended Blade Components

6. Better Syntax for Event Listening

-> In the previous versions of Laravel, when creating a closure based event listener there was much repetition and a cumbersome syntax.

Better Syntax for Event Listening 1 of 2

In Laravel 8 it’s simpler and cleaner:

Better Syntax for Event Listening 2 of 2

7. Queueable Anonymous Event Listeners

-> In Laravel 8 it is possible to create queueable closure from anywhere in the code. This will create a queue of anonymous event listeners that will get executed in the background. This feature makes it easier to do this, while in previous versions of Laravel you would need to use an event class and an event listener (using the ShouldQueue trait).

Queueable Anonymous Event Listeners

8. Maintenance Mode

Maintenance Mode 1 of 3

-> This is especially useful when you need to do some maintenance on your application and you want to take it down for your users but still let your developers investigate bugs. This will create a secret cookie that will be granted to whoever hits the correct endpoint, allowing it to use the application while in maintenance mode.

Maintenance Mode 2 of 3

-> Pre-rendering an error view is a safe way for not exposing errors to your end user when your application is down (during a new deployment, for example). The Laravel 8 framework guarantees that your predefined error page will be displayed before everything else from the application.

Maintenance Mode 3 of 3

-> This combines the new features and will make the application only display a single predefined route, while still allowing for the people who have the secret to test and debug. This can be very useful when launching a new app.

9. Closure Dispatch “Catch”

Closure Dispatch "Catch"

-> Laravel has a pretty robust queue system that accepts a closure queue that will get serialized and executed in the background. Now we have a way to handle failures in case your job fails.

10. Exponential Backoff Strategy

-> This is an algorithm that decreases the rate of your job in order to gradually find an acceptable rate.

Exponential Backoff Strategy

Now Laravel has this capability too, which is handy for jobs that deal with external APIs, where you wouldn’t want to try again in the same amount of time. It can also be used to dynamically generate the return array, setting different times to wait before retrying.

The above content is written by the help of moduscreate.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Back to top button