Laravel 5.5 LTS is Now Released

Published on by

Laravel 5.5 LTS is Now Released image

Version 5.5 of Laravel is now officially released! This release is jam-packed with goodies and improvements–here’s a quick video summarizing the highlight features:

Taylor Otwell recenly described his thoughts on Laravel 5.5 in this tweet:

Leave tomorrow for @LaraconEU. 5.5 next week also. Favorite release yet. Love the shape the framework is in. Never been happier with it. ????

— Taylor Otwell (@taylorotwell) August 25, 2017

Laravel 5.5 is the Next LTS Release

Laravel 5.5 is the next long term support (LTS) version of Laravel (the last being 5.1). LTS versions receive bug fixes for two years, and security fixes for three years.

General minor releases receive bug fixes for six months and security fixes for one year.

Whoops Package

You might recall the filp/whoops package from Laravel v4 provided elegant stack traces for your most frustrating debugging moments. The whoops package returns to Laravel 5.5!

Collection Dumping

Another great debugging feature (that I’ve seen previously as a package or macro) is collection dumping methods:

<?php
 
Song::all()
->filter
->platinum
->dump()
->filter(function ($song) {
return $song->released_on >= \Carbon\Carbon::parse('-10 years');
})
->dd();

Read our collection dumping post for more details.

Exception Rendering

Exceptions now can render a response if they define a public “response” method. Typically, in earlier versions of Laravel you might add a check to the App\Exceptions\Handler::render() method, and conditionally send back a response based on the exception type.

In 5.5, you can just throw the exception, and it can respond without additional logic in your handler:

<?php
 
// throw new TerribleSongException($song) in a controller...
 
namespace App\Exceptions;
 
use App\Song;
 
class TerribleSongException extends \Exception
{
/**
* @var \App\Song
*/
protected $song;
 
public function __construct(Song $song)
{
$this->song = $song;
}
 
/**
* @param \Illuminate\Http\Request $request
*/
public function render($request)
{
return response("The song '{$this->song->title}' by '{$this->song->artist}' is terrible.");
}
}

You can also implement the Responsable interface in your exception classes, and Laravel will respond automatically.

The Responsable Interface

The Responsable interface is another response addition to laravel that we’ve covered at Laravel news. A class implementing the interface can be returned from a controller method; the router now checks for an instance of Responsable when preparing the response from Illuminate\Routing\Router.

Here’s what an example might look like, leaving the response details to the NewSongResponse object:

public function store(Request $request)
{
$data = request()->validate([
'title' => 'required',
'artist' => 'required',
'description' => 'required',
'duration' => 'required|numeric',
'released_on' => 'required|date_format:Y-m-d',
'gold' => 'boolean',
'platinum' => 'boolean',
]);
 
$song = new Song($data);
$song->save();
 
return new NewSongResponse($song);
}

Here’s what the class might look like implementing the Responsable interface for a new song creation:

<?php
 
namespace App\Http\Responses;
 
use App\Song;
use Illuminate\Contracts\Support\Responsable;
 
class NewSongResponse implements Responsable
{
/**
* @var \App\Song
*/
protected $song;
 
/**
* @param \App\Song $song
*/
public function __construct(Song $song)
{
$this->song = $song;
}
 
public function toResponse($request)
{
if ($request->wantsJson()) {
return response()
->json($this->song)
->header('Location', route('songs.show', $this->song))
->setStatusCode(201);
}
 
return redirect()
->route('songs.show', $this->song);
}
}

In this simple example, you could automatically respond with JSON if you make a request via AJAX, and by default response with a redirect the songs.show route.

Request Validation Method

In past versions of Laravel you would pass the request instance to the $this->validate() method in a controller:

$this->validate(request(), [...]);

Now, you can just call validate on the request object:

$data = request()->validate([
'title' => 'required',
'artist' => 'required',
'description' => 'required',
'duration' => 'required|numeric',
'released_on' => 'required|date_format:Y-m-d',
'gold' => 'boolean',
'platinum' => 'boolean',
]);

Another nice benefit from this style of calling validation is that the return value acts like Request::only(), returning only the keys provided in the validation call. Returning only the validated keys is an excellent convention to use, avoiding Request::all().

Custom Validation Rule Objects and Closures

My favorite feature in Laravel 5.5 is hands-down the new custom validation rule objects and closures. Creating a custom rule object is an excellent alternative to creating custom rules with Validator::extend (which you can still use), because it’s more clear where the rule logic is located at a glance. A validation rule object might look like this:

<?php
 
namespace App\Rules;
 
use Illuminate\Contracts\Validation\Rule;
 
class CowbellValidationRule implements Rule
{
public function passes($attribute, $value)
{
return $value > 10;
}
 
public function message()
{
return ':attribute needs more cowbell!';
}
}

An example of using this validation rule looks like the following:

<?php
 
request()->validate([
'cowbells' => [new CowbellValidationRule],
'more_cowbells' => [function ($attribute, $value, $fail) {
if ($value <= 10) {
$fail(':attribute needs more cowbell!');
}
}]
]);

The closure style takes the attribute and value, and a fail parameter that you call if the validation rule should fail. The closure is a nice way to experiment with custom validation before you extract it to a dedicated rule object, or for one-off custom validation needs.

To create custom validation rule objects, you can use the new make:rule command:

$ php artisan make:rule MyCustomRule

We have a dedicated post to custom validation rules here on Laravel News, be sure to check it out!

Auth and Guest Blade Directives

We have written about Blade::if() directives in 5.5. A few new conditional directives in 5.5 are @auth and @guest.

Typically you might use something like the following to check for an authenticated user in Blade:

@if(auth()->check())
{{ -- authenticated --}}
@endif
 
@if(auth()->guest())

You can now use the following directives to achieve the same thing:

@auth
Welcome {{ user()->name }}!
@endauth
 
@guest
Welcome Guest!
@endguest

Frontend Presets

When you are starting a new project, Laravel 5.5 provides Vue.js scaffolding by default. In Laravel 5.5 you can now pick from a few presets and remove all frontend scaffolding with the “preset” Artisan command in Laravel 5.5.

If you look at the help, you can see that it allows you to pick “none,” “bootstrap,” “vue”, or “react”:

php artisan help preset
Usage:
preset <type>
 
Arguments:
type The preset type (none, bootstrap, vue, react)
 
# Use react
$ php artisan preset react
 
# Clear scaffolding
$ php artisan preset none

Separate Factory Files

Factory files were previously defined in one ModelFactory.php file. Now, you create different files for each model. You can create a factory file when you are creating a new model:

$ php artisan make:model -fm Post
 
# Or you can create a controller, migration, and factory
$ php artisan make:model --all

You can also create a factory file directly with “make:factory”:

$ php artisan make:factory --model=Example ExampleFactory

The migrate:fresh Migration Command

The new “migrate:fresh” migration command 5.5 is a nice addition to creating a clean database in development. The migrate:fresh command drops all the database tables and then runs the migrations.

You might be familiar with the existing migrate:refresh command, which rolls back migrations and then reruns them. Usually in development you want to just drop the tables, getting a fresh database, and running migrations.

The RefreshDatabase Trait

On the testing front, the RefreshDatabase trait is the new way to migrate databases during tests. This new trait takes the most optimal approach to migrating your test database depending on if you are using an in-memory database or a traditional database. The DatabaseTransactions and DatabaseMigrations traits are still available in 5.5, allowing you to upgrade without using the new RefreshDatabase trait.

The withoutExceptionHandling() method

The base test case inherits a method withoutExceptionHandling(), which allows you to disable exception handling for a test. Disabling exception handling allows you to catch the exception in your test and assert the exception instead of the exception handler responding. It’s also a useful debugging tool when your test is doing something you don’t expect, and you want to see the actual exception.

Automatic Package Discovery

The last feature we are going to look at is automatic package discovery. While Laravel packages aren’t usually hard to install, the package detection feature means you don’t have to set up providers or aliases. You can disable auto-discovery for specific packages.

Learn more about this feature from the Taylor Otwell’s article on this feature, and on our post.

Learning More About Laravel 5.5

Make sure to check out our Laravel 5.5 content for a more in-depth look. Laracasts has a complete series available on all of these features. Also, check out the official documentation, release notes, and the upgrade guide.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
A Resize Plugin for Alpine.js image

A Resize Plugin for Alpine.js

Read article
How to Migrate MySQL from DBngin to Laravel Herd image

How to Migrate MySQL from DBngin to Laravel Herd

Read article
Learn to master Query Scopes in Laravel image

Learn to master Query Scopes in Laravel

Read article
How to Redirect Uppercase URLs to Lowercase with Laravel Middleware image

How to Redirect Uppercase URLs to Lowercase with Laravel Middleware

Read article
PHP 8.4 Alpha 1 is now out! image

PHP 8.4 Alpha 1 is now out!

Read article
Generics Added to Eloquent Builder in Laravel 11.15 image

Generics Added to Eloquent Builder in Laravel 11.15

Read article