What's new in Laravel 5.6

whats-new-laravel-5-6-header.png

An overview of the new features and functionality in Laravel 5.6\.

Introduction

Laravel 5.6 was released shortly before this year’s Laracon online. This release continues the improvements made in Laravel 5.5 by adding more new features and improvements. In this article, I’ll cover the new features and improvements added to Laravel 5.6.

Let’s start by listing each of them, then we’ll go over them one after the other:
– Bootstrap 4
– Argon2 password hashing
– API controller generation
– Logging improvements
– Single server task scheduling
– Dynamic rate limiting
– Broadcast channel classes
– Model serialization improvements
– Eloquent date casting
– Blade component aliases
– UUID methods
– Collision

Now let’s go over each of them.

Bootstrap 4

Bootstrap 4 has been officially released after over two years of it being in development. In this vein, all frontend scaffolding such as the authentication boilerplate, example Vue component and even the pagination link generation in Laravel have been upgraded to use Bootstrap 4.

If you are upgrading your application from Laravel 5.5, you can continue to use Bootstrap 3 by adding the line of code below to the boot() method of app/Providers/AppServiceProvider:

1public function boot ()
2    {
3      Paginator::useBootstrapThree();
4    }

This will allow your application to use Bootstrap 3 as the default styling for pagination links.

Argon2 password hashing

With the release of PHP 7.2, which supports argon2 password hashing, Laravel now supports password hashing via the Argon2 algorithm. A new config/hashing.php configuration file is now being shipped with Laravel, which can be used to configure the default hash driver for your application.

However, to use argon2 password hashing, your application must be running on PHP 7.2.0 and above.

API controller generation

Laravel 5.6 makes it much easier to build APIs with Laravel. It introduces a new --api switch to the make:controller Artisan command:

1$ php artisan make:controller API/BookController --api

This will generate BookController with only the methods (index, store, update and destroy) needed when building APIs. This prevents having create() and edit() littering around or having to manually delete them yourself, since they are not useful when building APIs.

This introduction, combined with the apiResource() while defining resourceful routes, means awesome experience building API with Laravel. To learn how to combine these features together with API resources, see my other tutorial on [Build robust API with Laravel API Resources].

Logging improvements

Logging in Laravel has become a lot better with the release of Laravel 5.6. The logging system now has it own dedicated config/logging.php configuration file. You can now easily build logging stacks that send log messages to multiple handlers.

1'channels' => [
2      'stack' => [
3        'driver' => 'stack',
4        'channels' => ['syslog', 'slack'],
5      ],
6      'syslog' => [
7        'driver' => 'syslog',
8        'level' => 'debug',
9      ],
10      'slack' => [
11        'driver' => 'slack',
12        'url' => env('LOG_SLACK_WEBHOOK_URL'),
13        'username' => 'Laravel Log',
14        'emoji' => ':boom:',
15        'level' => 'critical',
16      ],
17    ],

From the config file above, we are stacking multiple channels (syslog and slack) so that all debug level messages will be sent to the system log while all error level messages be sent to Slack so that your team can quickly react to errors.

It is also now easier to customize existing log channels using the logging system’s new tap functionality. For more information, check out the docs.

Single server task scheduling

Another addition made to Laravel 5.6 is single server task scheduling, which allows the ability to limit a scheduled job to only execute on a single server. Before Laravel 5.6, If your application is running on multiple servers and the task scheduler is also running on these servers, then the scheduled tasks will run multiple times.

Now you can indicate that the task should run on only one server, by making use of the onOneServer() method:

1$schedule->command('report:generate')
2              ->weekly()
3              ->onOneServer();

To utilize this feature, your application must be using the memcached or redis cache driver as your application’s default cache driver. In addition, all servers must be communicating with the same central cache server. For more information, check out the docs.

Dynamic rate limiting

Laravel has a throttle middleware that can be used to rate limit access to routes within your application. The middleware can be used as below:

1Route::get('/user', function () {
2      return 'access granted!';
3    })->middleware('throttle:10,1');

In the above example, we pass in the maximum number (10 in this case) of requests that can be made to the /user route and also the time in minutes (1 in this case) which the requests will span. As you can see, we are hard coding in these values. This is fine until, for example, you want to control access to the route base on the user’s privilege or something. Prior to Laravel 5.6, there is no way to easily achieve this.

With the addition of dynamic rate limiting in Laravel 5.6, we can now dynamically pass the number of requests to be made to the throttle middleware. To achieve the scenario above, we can have a rate_limit column on our users table, which will hold the number of requests a particular user can make. Then we can use it as below:

1Route::get('/user', function () {
2      return 'access granted!';
3    })->middleware('throttle:rate_limit,1');

Now any user access to the /user route will be determined by the value on the rate_limit column. Of course, how the value in the rate_limit column is determined will depend on your application. For more information, check out the docs.

Broadcast channel classes

Previously when broadcasting on a private channel, we have to define a Closure in the routes/channels.php file which is used to determine whether a user is logged in or not. This can easily become bulky depending on your application. So in Laravel 5.6, instead of using Closures to authorize channels, you may now use channel classes. We can make use of the new make:channel Artisan command to generate broadcast channel classes:

1$ php artisan make:channel ChatChannel

This will create a new ChatChannel channel class in the App/Broadcasting directory.

Next, we can register the channel in the routes/channels.php file:

1use App\Broadcasting\ChatChannel;
2
3    Broadcast::channel('chat', ChatChannel::class);

Then we’ll define the authorization logic in the join() method of the ChatChannel channel class. The join() method will contain the authorization logic that we would have typically placed in your channel authorization closure:

1<?php
2
3    namespace App\Broadcasting;
4
5    use App\User;
6    use Illuminate\Support\Facades\Auth;
7
8    class ChatChannel
9    {
10      /**
11      * Create a new channel instance.
12      *
13      * @return void
14      */
15      public function __construct()
16      {
17        //
18      }
19
20      /**
21      * Authenticate the user's access to the channel.
22      *
23      * @param  \App\User  $user
24      * @return array|bool
25      */
26      public function join(User $user)
27      {
28        return Auth::check();
29      }
30    }

For more information, check out the docs.

Model serialization improvements

Prior to Laravel 5.6, queued models would not be restored with their loaded relationships intact. With the improvement to Laravel 5.6, now relationships that were loaded on the model when it was queued are automatically re-loaded when the job is processed by the queue.

Eloquent date casting

It’s now possible to individually customize the format of Eloquent date cast columns:

1protected $casts = [
2      'birthday' => 'date:Y-m-d',
3      'last_seen_at' => 'datetime:Y-m-d H:00',
4    ];

We simply specify the desired date format within the cast declaration. Now this format will be used when serializing the model to an array or JSON.

Blade component aliases

Another new feature in Laravel 5.6 is Blade component aliases. You can now alias your Blade components stored in a sub-directory for easier access. Let’s say, for instance, we have a Blade component that is stored at resources/views/components/notification.blade.php. We can use the component method to alias the component from components.notification to notification:

1Blade::component('components.notification', 'notification');

Then we can render it using a directive:

1@notification('notification', ['type' => 'danger'])
2      Your account has been successfully upgraded!
3    @endnotification
4
5    // we can even omit the component parameters if it has no additional slots
6    @notification
7      Your account has been successfully upgraded!
8    @endnotification

For more information, check out the docs.

UUID methods

Laravel 5.6 introduces two new methods for generating UUIDs: Str::uuid and Str::orderedUuid:

1use Illuminate\Support\Str;
2
3    $uuidString = (string) Str::uuid();
4
5    $orderedUuidString = (string) Str::orderedUuid();

The orderedUuid method will generate a timestamp-first UUID that is more easily and efficiently indexed by databases such as MySQL. Each of these methods returns a Ramsey\Uuid\Uuid.

Collision

Laravel 5.6 applications now contain a dev composer dependency for a package called Collision, which is a community package developed and maintained by Nuno Maduro. Collision is a detailed and intuitive error handler framework for console/command-line PHP applications.

This packages provides beautiful error reporting when interacting with your Laravel application on the command line:

laravel command line error reporting

Miscellaneous

  • Laravel 5.6 requires PHP 7.1.3 and above.
  • The Artisan optimize command was deprecated as of 5.5 and has been removed officially from 5.6.
  • Laravel 5.6 includes two new Blade directives: @csrf and @method.

You can view the complete change logs on GitHub.

Conclusion

In this article, we looked at what’s new in Laravel 5.6 and went through lots of the feature and improvement. You should check the Laravel release notes for more information and the upgrade guide to see how to upgrade your application to Laravel 5.6.