Laravel 6

Laravel 6 has already stepped in the market. No wonder, it possesses some considerable features and upgrades. Everyone, from developers to agencies to well-established brands, has started to leverage its power. However, there are still who are unaware or not completely aware of the improvements and additions. If you are one of them, this article is for you.

To know the exact additions or enhancements and their respective benefits, we had a word with one of our Laravel Certified Developers – Maneesh Kumar Sharma. His experience and knowledge with Laravel have given us some remarkable projects – both in the form of websites and apps.

Below is the gist of what Maneesh told us about Laravel 6, including its features and benefits.

SEMANTIC VERSIONING
Laravel 6 now follows semantic versioning for future releases. It will keep the framework’s minor releases consistent with package management system and ensure they are compatible with other dependent Laravel packages.
The following example will demonstrate how Semantic Versioning can be useful. Consider a library called “Firetruck.” It requires a Semantically Versioned package named “Ladder.” At the time Firetruck is created, Ladder is at version 3.1.0. Since Firetruck uses some functionality that was first introduced in 3.1.0, you can safely specify the Ladder dependency as greater than or equal to 3.1.0 but less than 4.0.0. Now, when Ladder version 3.1.1 and 3.2.0 become available, they will be compatible with the existing dependent software.

COMPATIBILITY WITH LARAVEL VAPOR
Laravel Vapor is a serverless deployment platform for Laravel, which helps to manage Laravel application on AWS Lambda, working with SQS queues, databases, Redis clusters, networks, CloudFront CDN, and more. You just have to create an account in Laravel Vapor and install Laravel Vapor CLI in your Laravel project to use it.

  • Choose a billing plan
    Before creating your first project, you need to subscribe to a billing plan.
  • Connect an aws account
    To get started with Vapor, you need to link an AWS account.
  • Create your first project
    Vapor is organized around projects. Projects can contain as many environments as you wish and each environment receives its very own URL. To create a project, install the Vapor CLI, login, and run the vapor init command. To learn more, check out the documentation.

Installing The Vapor CLI

composer require laravel/vapor-cli

composer global require laravel/vapor-cli

When the CLI is installed per project, you need to execute it via the vendor/bin directory of your project. For instance, to view all of the available Vapor CLI commands, you may use the list command:

php vendor/bin/vapor list

IMPROVED EXCEPTIONS VIA IGNITION
Laravel 6 uses Ignition, a beautiful and customizable default error page. It offers improved UX, lets you share error, track exception, line number handling and solutions which can be used for common problems.

IMPROVED AUTHORIZATION RESPONSES
Laravel 6 allows you to use Gate::inspect method for retrieving the response and showing messages to end users using authorization response messages. Also, the authorization response messages will be automatically returned to frontend while using Gate::authorize, $this->authorize from routes or controllers.

For example, policy methods generally return simple boolean values. However, sometimes you may wish to return a more detail response, including an error message. To do so, you may return a Illuminate\Auth\Access\Response from your policy method:

<?php

namespace App\Policies;

use App\Post;
use App\User;
use Illuminate\Auth\Access\Response;

class PostPolicy
{
/**
* Determine if the given post can be updated by the user.
*
* @param \App\User $user
* @param \App\Post $post
* @return bool
*/
public function update(User $user, Post $post)
{
return $user->id === $post->user_id
? Response::allow()
: Response::deny(‘You do not own this post.’);
}
}

Here you may use new Gate::inspect method that will return the full authorization response returned by the gate:

$response = Gate::inspect(‘update’, $post);

if ($response->allowed()) {
// The action is authorized…
} else {
echo $response->message();
}

You can also use Gate::authorize method to throw an AuthorizationException – in case the action is not authorized, the error message provided by the authorization response will be propagated to the HTTP response:

Gate::authorize(‘update’, $post);

JOB MIDDLEWARE
Just like the middleware for routes, Laravel has introduced middleware for jobs. This can be used for preprocessing before the core logic is executed in handle() method of jobs and create the job middleware. After this, you can attach the new middleware by defining middleware() method in job class returning.

For example, in previous releases of Laravel, you may have wrapped the logic of a job’s handle method after some preprocessing tasks or checks:

/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//some checks and preprocessing code before core logic

//then core logic
}

In Laravel 6, this logic may be extracted into a job middleware, allowing you to keep your job’s handle method free of any job specific preprocessing tasks:

<?php

namespace App\Jobs\Middleware;

use Illuminate\Support\Facades\Redis;

class JobMiddleware
{
/**
* Process the queued job.
*
* @param mixed $job
* @param callable $next
* @return mixed
*/
public function handle($job, $next)
{
//some checks and preprocessing code before core logic

$next($job);
}
}

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

use App\Jobs\Middleware\JobMiddleware;

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

LAZY COLLECTIONS
Laravel 6 has introduced a supplement to Collection class which makes use of PHP’s generators and allows users to work with large datasets using less memory. LazyCollection::make() along with ‘yield’ PHP function lets you iterate through large dataset without loading all at once. Also in Laravel 6, query builder’s cursor method now returns LazyCollection instance, which means the dataset will not be loaded in one go and use only one query against the database.

Instead of reading the entire file into memory at once, lazy collections can 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;
});

Whereas with Laravel 6, the query builder’s cursor method now returns a LazyCollection instance.

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

In this example, the filter callback above is not executed until we actually iterate over each user individually, allowing for a drastic reduction in memory usage:

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

So, only user model is fetched in memory and filtered into $users variable collection.

ELOQUENT SUBQUERY ENHANCEMENTS
Laravel 6 has also introduced new enhancements and improvements to database subquery support in Eloquent models. Now subquery functionality is available to the select, addSelect and query builder’s orderBy function methods.

Using the subquery functionality available to the select and addSelect methods, we can select all of the Categories and the name of the users that have been added using a single query.

use App\Category;
use App\User;

return Category::addSelect([‘last_flight’ => Category::select(‘name’)
->whereColumn(‘category_id’, ‘categories.id’)
->orderBy(‘created_at’, ‘desc’)
->limit(1)
])->get();

Here is query builder’s orderBy example. We may use this functionality, for example, to sort all categories based on when the latest User is added to that Category. Again, this may be done while executing a single query against the database:

return Category::orderByDesc(
User::select(‘created_at’)
->whereColumn(‘category_id’, ‘categories.id’)
->orderBy(‘created_at’, ‘desc’)
->limit(1)
)->get();

LARAVEL UI
The frontend scaffolding is extracted into a separate laravel/ui Composer package. So, now Bootstrap or Vue code is present in default framework scaffolding and the make:auth command has been extracted. You may install the ‘laravel/ui’ package and use the ui Artisan command to install the frontend scaffolding.

composer require laravel/ui –dev

php artisan ui vue –auth

Well, this is all that Laravel 6 has brought with itself. The features seem quite useful in creating a rich user experience and interface.

Try it today and share your experience with us. If you come across any difficulties, don’t worry, we are ready to help you.

Author’s Bio

Maneesh Sharma - Sr. Laravel Developer

A Laravel lover and developer by profession, Maneesh is one of the certified developers at Nethues. Always stuck to his computer screen, he barely deviates to anything except coding, not even eating for that matter.

Read more posts by

Want to hire certifiedLaravel developer for your project?

Let's Talk

Our Latest Updates

February 5, 2024
Leverage 11 AI Tools for Business Growth & High Productivity in 2024

AI has become an integral part of businesses for staying competitive and making fast-paced decisions. Generative AI is ruling major parts of the business processes…

January 17, 2024
Guide to Understanding MVP in Software Development

While studying the complex realm of technologies and IT solutions, you must have encountered MVP in Software Development. This software development approach allows businesses to…

product
December 15, 2023
Unlocking the Business Benefits of MVP Development for Startups in 2024

Building a minimum viable product or MVP allows startups to validate ideas faster and find genuine data on their demand, further shaping the ideas into…