What's new in Laravel 5.8
Sarthak
4 years ago

0

Laravel 5.8 - 21 important update you should care about.

Laravel 5.8 is now released and this release has many many improvements, addition and some breaking changes.

I. Major Upgrade or Breaking Changes

  1. Caching TTL
  2. Deprecated Helper Functions
  3. Dotenv 3.0
  4. Carbon version 2
  5. Notifications Package
  6. Testing PHPUnit 8
  7. Password Length

II. Improvements

  1. Error Page
  2. Artisan Call Improvements
  3. Email Validation
  4. Eloquent Resource Key Preservation
  5. Higher Order orWhere Eloquent Method
  6. JSON in MYSQL
  7. Correct Pluralisation
  8. Mock / Spy Testing Helper Methods

III. New Addition

  1. Artisan Serve Improvements
  2. Auto-Discovery Of Model Policies
  3. HasOneThrough Relationship
  4. Token Guard Token Hashing
  5. Default Scheduler Timezone
  6. Multiple Broadcast Authentication Guards

Caching TTL

Caching in previous laravel versions was set with time in minutes. So if you have given any integer to cache methods then that was considered as time in minutes.

With laravel 5.8, that is directly converted to seconds for more precise and concise setting of cache timing. So make sure you will change that time from minutes to seconds.

// Laravel 5.7 - Store item for 5 minutes...
Cache::put('foo', 'bar', 5);

// Laravel 5.8 - Store item for 5 seconds...
Cache::put('foo', 'bar', 5);

Deprecated Helper Functions

All array_* and str_* global helpers have been deprecated. This means from laravel 5.9 there will be no longer available.

But don't worry about this removal as for now you can easily use there functions using Illuminate\Support\Arr and Illuminate\Support\Str methods directly.

And after laravel 5.8 they will be packed in a separate package.

Dotenv 3.0

Laravel 5.8 is now ships with PHP dotenv 3.0 which includes the many new features.

  1. No trimming of values from .env file, you get them exactly as-is now. so spaced are also considered.
  2. Support for multi-line variables.
  3. Accept a list of paths to try in order looking for the dotenv file, rather than a single path.
  4. Stronger validation of variable names to avoid silent failures or obscure errors

Check out PHP dotenv 3.0 github release notes.

Notifications Package

This is a major change to be considered. With laravel 5.8, slack notification and nexmo notification is now moved to dedicated first-party package and no longer is a part of laravel core component. Now you need to install these via composer.

composer require laravel/nexmo-notification-channel
composer require laravel/slack-notification-channel

Testing PHPUnit 8

By default, Laravel 5.8 uses PHPUnit 7. However, you may optionally upgrade to PHPUnit 8, which requires PHP >= 7.2. To this change, The setUp and tearDown methods now require a void return type:

protected function setUp(): void
protected function tearDown(): void

Carbon version 2

Laravel 5.8 can able to use either Carbon v1 or Carbon v2, including the ability to use CarbonImmutable, and even make CarbonImmutable the default. Localization has changed quite a bit in Carbon v2, with much better internationalization support offered than v1. Learn more about Carbon 2.0

New Default Password Length

The required password length when choosing or resetting a password was changed to at least eight characters.

Mock/Spy Testing Helper Methods

Mocking any class in laravel is now even more simpler. check this demo.

// Laravel 5.7
$this->instance(Stripe::class, Mockery::mock(Stripe::class, function ($mock) {
    $mock->shouldReceive('charge')->once();
}));

// Laravel 5.8
$this->mock(Stripe::class, function ($mock) {
    $mock->shouldReceive('charge')->once();
});

Artisan Serve Improvements

Until now with laravel previous versions, Artisan's serve command would serve your application on port 8000. So, if another serve command to start a server started, an attempt to serve a second application via serve would fail. But now in Laravel 5.8, serve will now scan for available ports up to port 8002 and will serve multiple applications at once.

Auto-Discovery Of Model Policies

Now with laravel 5.8, you don't have to register your Policies untill they are at their conventional directory which is aap/policies. In addition, the policy name must match the model name and have a Policy suffix. So, a Product model would correspond to a ProductPolicy class.

HasOneThrough Relationship

ELoquent now support a new type of relationship which is hasOneThrough relationship type.

Imagine a scenario when a user has a Product model and that product has a ProductDetail model, now with this relationship you can easily get user's product details via Product model.

/**
 * Get the product details of user.
 */
public function productDetails()
{
    return $this->hasOneThrough(ProductDetail::class, Product::class);
}

Token Guard Token Hashing

Now with laravel 5.8, you can easily setup your API token system on laravel itself and can store token with SHA-256 hash. This means you don't have to specifically use laravel passport just for authentication or any jwt package. But if you wish to use any package you are totally free as passport package is there to user. Learn more at API authentication documentation.

Default Scheduler Timezone

Yes with laravel you can define your timezone for a scheduled task. but if you have many scheduled tasks running and all are using same timezone then it will be repetitive and pain to define same timezone for each scheduled task.

Now comes laravel 5.8 default scheduler timezone, you may now define a scheduleTimezone method in your app/Console/Kernel.php file.

This timezone defined in Kernel file will be attached to every scheduler you have. In your app/Console/Kernel.php

/**
 * Get the timezone that should be used by default for scheduled events.
 *
 * @return \DateTimeZone|string|null
 */
protected function scheduleTimezone()
{
    return 'Asia/Kolkata';
}

Multiple Broadcast Authentication Guards

Now authenticate private or presence channels with different middlewares, other than the default middleware of the project.

Broadcast::channel('channel'Name, function() {
    // ...
}, ['guards' => ['web', 'admin']])

Artisan Call Improvements

If you want to programmatically call Artisan command then you generally use Artisan::call method. But what if you need to pass some options to the command. Here is a simple way to do so.

Artisan::call('migrate:install', ['database' => 'foo']);

But with laravel 5.8, its just like a command you write on console/terminal. Super easy to define options inline to command.

Artisan::call('migrate:install --database=foo');

Email Validation

Improvement in email validation is added to laravel 5.8. Previously the email like example@naïve.com was considered as invalid, but now it will pass the email validation and thanks to adoption of egulias/email-validator package.

Higher Order orWhere Eloquent Method

Previously, combining various scoped query with or query require a closure to be defined.

// scopeActive and scopeEmailVerified methods defined on the User model...
$users = App\User::emailVerified()->orWhere(function (Builder $query) {
    $query->active();
})->get();

But now with laravel 5.8 you don't need that closure anymore.

$users = App\User::emailVerified()->orWhere->active()->get();

Correct Pluralisation

A fix for pluralisation of your Models is corrected in laravel 5.8

in Laravel 5.7, app\Advice.php will be pluralized as advice only but app\Customer_advice will be pluralized as customer_advices, which is incorrect.

In laravel 5.8 app\Advice.php will be pluralized as advice only but app\Customer_advice will be pluralized as customer_advice, which is correct.

JSON in MYSQL

This is a fix from previous versions where when you store any json data in your database, then query builder will return quoted string '"hello"'. But with laravel 5.8, they will be unquoted which means simple string is returned 'hello'.

Eloquent Resource Key Preservation

Previously When we use eloquent resource collection, then it will reset the collection's key and simple order will be returned.

But now you can set preserveKeys property to your resource class to preserve the keys of your collection.


<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * Indicates if the resource's collection keys should be preserved.
     *
     * @var bool
     */
    public $preserveKeys = true;
}

Error Page

Now the error page is looking more modern, minimalistic and cool.

Laravel 5.7 also had nice error pages but that was not suitable for every situation. A simple error page can be used everywhere.