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:

    public function boot ()
    {
      Paginator::useBootstrapThree();
    }

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:

    $ 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.

    'channels' => [
      'stack' => [
        'driver' => 'stack',
        'channels' => ['syslog', 'slack'],
      ],
      'syslog' => [
        'driver' => 'syslog',
        'level' => 'debug',
      ],
      'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'username' => 'Laravel Log',
        'emoji' => ':boom:',
        'level' => 'critical',
      ],
    ],

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:

    $schedule->command('report:generate')
              ->weekly()
              ->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:

    Route::get('/user', function () {
      return 'access granted!';
    })->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:

    Route::get('/user', function () {
      return 'access granted!';
    })->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:

    $ 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:

    use App\Broadcasting\ChatChannel;

    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:

    <?php

    namespace App\Broadcasting;

    use App\User;
    use Illuminate\Support\Facades\Auth;

    class ChatChannel
    {
      /**
      * Create a new channel instance.
      *
      * @return void
      */
      public function __construct()
      {
        //
      }

      /**
      * Authenticate the user's access to the channel.
      *
      * @param  \App\User  $user
      * @return array|bool
      */
      public function join(User $user)
      {
        return Auth::check();
      }
    }

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:

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

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:

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

Then we can render it using a directive:

    @notification('notification', ['type' => 'danger'])
      Your account has been successfully upgraded!
    @endnotification

    // we can even omit the component parameters if it has no additional slots
    @notification
      Your account has been successfully upgraded!
    @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:

    use Illuminate\Support\Str;

    $uuidString = (string) Str::uuid();

    $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.