Laravel 5.8 - What’s New in Laravel 5.8?

by jay patel




Introduction:

PHP laravel introduce new version laravel 5.8 with new features. laravel 5.8 is released now and available for all. laravel 5.8 added new feature like cache TTL changes and lock, Deprecate string and array helper methods, update email validation, Automatic Policy Resolution, PHP dotenv, added firstWhere function in collection, database mysql json value etc.

As always, before upgrading a Laravel version, be sure to carefully read and understand the upgrade guides to ensure a smooth upgrade process.

we will see list of main changes in this tutorial about what's new in laravel 5.8 version.

 

Let's see one by one important updates on laravel 5.8 version. that will help to use in your next project. laravel 5.8 does not change directory structure, so don't worry about that. let's see bellow list.

Caching —TTL now in seconds instead of minutes:

If you are using Laravel’s caching functions take note that if you are passing an integer to the cache function in 5.8 it will apply the time to live in seconds and not  minutes  as it currently is in 5.7, so this command:

 

 

Cache::put('foo', 'bar', 30);

 

 

Will store the item for 30 minutes in Laravel 5.7 and 30 seconds in Laravel 5.8. A simple but important difference!

Deprecated String and Array Helpers Functions

All string and array global functions removed in laravel 5.8. you can not use any more functions like array_add, array_first, array_last, str_slug, str_random etc, instead of this functions you can use same method using Illuminate\Support\Arr and Illuminate\Support\Str facade like as bellow example.

 

 

use  Illuminate \ Support \ Arr ;

$array  =  Arr : : add ( [ ' name '  =>  ' ABC ' ] , ' price ' ,  200 ) ;

//  [ ' name '  =>  ' ABC ' ,  ' price '  =>  200 ]

 

 

 

use  Illuminate \ Support \ Str ;

$random  =  Str : : random ( 10 ) ;

 

 

In fact, if you check the 5.8 code for array_* and str_* global helpers you’ll see they already simply use the facade version.

Carbon version 2 support:

You will now have the option of using Carbon 1 or Carbon 2 for your DateTime functions in Laravel 5.8. Check the Carbon migration guide if you intend to use Carbon 2.

dotenv 3.0:

Laravel 5.8 will support the relatively new dotenv 3.0 to manage your project’s .env environment file.

phpdotenv 3.0

The key new features in dotenv 3.0 are support for multiline strings and white space at the end of strings in your environment file, for example, something like:

 

 

DEVELOPMENT_APP_KEY = "specialstringfor thisapp"

 

 

Will only return specialstringfor, whereas in 5.8 the whole specialstringfor thisapp will be parsed. It will also respect any spaces at the end of the string, which were previously stripped from the environment variables.

This is a great update for situations where multiline API keys are required for security.

New Default Password Length

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

Mailables directory name change:

This is less of a new feature but an important element you will need to be aware of when upgrading a project.

If you have mailables in your project and you have customised the components using the php artisan vendor:publish command, the folder names have changed slightly, namely the
/resources /views /vendor /mail /markdown directory is now named
/resources /views /vendor /mail /text.

This is because both folders can contain markdown code for making good looking responsive html templates with plain text fallbacks. It’s more logical to call the markdown folder text.

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

 

 

Nexmo and Slack Notification channels:

The Nexmo and Slack Notification channels have been removed from the main Laravel project and extracted into first-party packages.

To continue using Slack or Nexmo functionality in your project you’ll need to use:

 

 

composer  require  laravel / nexmo - notification - channel

composer  require  laravel / slack - notification - channel

 

 

They can then be configured and used as before.

New error page templates:

Laravel 5.8 will ship with new error pages featuring a very minimalist design that is intended to be more suitable for a range of websites and web apps without needing to be re-designed to fit a theme.

Laravel 5.7 404 view (top) and 5.8 404 view (bottom)

Laravel 5.8 404 error page

You can still customise the error pages or import your previous designs if you prefer them.

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:

Laravel’s built in validation rule for email in 5.8 will now allow for international characters in email addresses.

If you have the following validation code:

 

 

$request -> validate ( [

' email '  =>  ' email ' ,

] ) ;

 

 

And attempt to validate an email address such as swe@bär.au  in 5.7, it will fail. However it will pass validation in 5.8.

In 5.7 the validation logic did not match with the logic used by SwiftMailer (the PHP mailer library used by Laravel), but now they both conform to RFC6530 compliance.

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.

 

 

namespace App\Http\Resources;

useIlluminate\Http\Resources\Json\JsonResource;

classUserextendsJsonResource

{

/**

* Indicates if the resource's collection keys should be preserved.

*

* @var bool

*/

public $preserveKeys = true;

}

 

 

Higher Order orWhere Eloquent Method

In previous versions of Laravel, we can combine the model scopes using or query operator which requires a Closure callback. Like below:

 

 

$posts  =  App \ Post : : popular ( ) -> orWhere ( function ( Builder  $query )  {

$query -> active ( ) ;

} ) -> get ( ) ;

 

 

Laravel 5.8 introduces a “higher order” orWhere method that allows you to fluently chain these scopes together without the use of Closures:

 

 

$posts  =  App \ Post : : popular( ) -> orWhere -> active( ) -> get( ) ;

 

 

JSON values in MySQL:

If you are storing JSON values in MySQL and MariaDB database columns, in 5.7 Laravel would return values wrapped in double quotes. 5.8 returns the same values in cleaner strings.

The following is the example from the Laravel upgrade guide which illustrates the change:

 

 

$value   =   DB : : table ( ' users ' ) -> value ( ' options -> language ' ) ;

 

 

dump ( $value ) ;

 

//  Laravel  5.7 …

' " en " '

 

//  Laravel  5.8 …

' " en " '

 

 

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.

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 ( ) ;

} ) ;

 

 

Added Blade Template File Path in Compiled file

As we know laravel compile blade file, but as you can see your laravel 5.7 or laravel 5.6 Compiled blade files there are no file path of complied.

In laravel 5.8 they provide path of blade template file path as shown in example:

laravel blade template 3.0

 

Artisan Serve Improvements

Currently when we run php artisan serve command, Laravel server your application on port 8000. If another serve command is running and listening on this port, an attempt to serve the application will fail. In Laravel 5.8, php artisan serve command now scan for available port up to port 8009, which will allow you to serve multiple applications.

Auto-Discovery Of Model Policies

Now with laravel 5.8, you don't have to register your Policies until 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

In Laravel 5.8, we will have a new relationship called HasOneThrough. For example, if we have a Comment model which has one User and an User model has one Profile model. We can use HasOneThrough relationship to get the profile for a given comment. Like below,

 

 

/ * *

*  Get the user profile for the comment.

* /

public  function  profile ( )

{

return  $this -> hasOneThrough ( Profile : : class , User : : 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

When we define a scheduled task we can use the timezone method like below,

 

 

$schedule -> command ( ' inspire ' )

-> hourly ( )

-> timezone ( ' Europe/London ' ) ;

 

 

What if you have a number of tasks and you have to set the timezone on every one of them?

In Laravel 5.8, you can define a new method called scheduleTimezone in 
app/Console/Kernel.php file. This method should return the default timezone which should be assigned to all tasks.

 

 

/ * *

* Get the timezone that should be used by default for scheduled events.

*

* @return  \DateTimeZone | string | null

* /

protected  function  scheduleTimezone ( )

{

return ' Europe/London ' ;

}

 

 

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 ' ] ] )

 

 

So,here cover the main changes in Larael 5.8 which you should be aware of. You can check for more details about all new features and changes at the Laravel Documentation‘s release notes section.



Leave a Reply

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

   Confirm you are not a spammer
   Notify me of follow-up comments by email.