JSON Type Assertions and a "prohibited" Validation rule Are Now In Laravel 8.34

News

March 24th, 2021

laravel8.jpg

The Laravel team released 8.34 with type assertions in the fluent JSON API, a 'prohibited' validation rule, a new event fake assertion, and the latest changes in the 8.x branch:

Exclude Path Option In the route:list Command

@JUNO_OKYO contributed a --without-path flag to the route:list command. This flag will accept a comma-separated list of route paths to exclude. Some packages add routes that may not be of concern to application developers utilizing a package. In that case, they can use:

php artisan route:list --exclude-path=telescope

String remove() Methods

Luke Downing contributed a remove() method to the Str and Stringable classes in Illuminate\Support . The remove() method will accept string characters to remove from a string:

// Fbar
Str::remove('o', 'Foobar');
Str::of('Foobar')->remove('o');

// Fbr
Str::remove(['o', 'a'], 'Foobar');
Str::of('Foobar')->remove(['o', 'a']);

// oobar (case-insensitive)
Str::remove('f', 'Foobar', false);
Str::of('Foobar')->remove('f', false);

Assert Type in Fluent JSON Assertions

Sven Luijten contributed whereType and whereAllType methods to fluent JSON assertions API:

$response->assertJson(fn (Assert $json) => $json
    ->whereType('name', 'string')
    ->whereAllType(['name' => 'string', 'age' => 'integer'])
);

// Union types are supported
$response->assertJson(fn (Assert $json) => $json
    ->whereType('name', 'string|null')
    ->whereType('age', ['integer', 'null'])
);

Prohibited Validation Rule

Philo Hermans contributed a new prohibited validation rule that will fail validation if a prohibited field (immutable) is present in the request body. This is useful if you have an immutable value that should not change, but your API doesn't fail when the user tries to update that value.

Instead you can return a validation error if you detect an immutable property in the API request:

// PUT /api/licenses/123-456
// {"name":"hello-world", "key":"random-key"}

$validated = $request->validate([
    'name' => 'required|max:255',
    'key' => 'prohibited',
]);

// Response: 422
// The key field is prohibited

Strict Validation for the Distinct Validation Rule

@gilbertorussi contributed a strict parameter for the distinct validation rule. The distinct rule uses PHP's in_array function, and if you pass the strict parameter the in_array check will be strict. Here's an example from the pull request:

$v = new Validator(
    $trans,
    ['foo' => ['0100', '100']],
    ['foo.*' => 'distinct:strict']
);

// Without strict the above data would fail validation.
$this->assertTrue($v->passes());

Assert Event Listeners

Luís Dalmolin contributed the ability to assert if event listeners are attached to the expected events:

Event::fake();

Event::assertListening(
    Registered::class,
    SendEmailVerificationNotification::class
);

Event::assertListening(
    Illuminate\Auth\Events\Login::class,
    [UserEventSubscriber::class, 'handleUserLogin']
);

Lazy Query Build Method

Joseph Silber contributed lazy() and lazyById() methods to the query builder, which will "chunk results behind the scenes, and return a single LazyCollection of results."

$lazyCollection = User::lazy();

User::lazy()->each->greet();
User::lazy()->map->calculateOutstandingBalance();

Documentation on lazy() will be available soon, but for now, I'd check out Pull Request #36699 for more details on why this method is useful and how it works.

Release Notes

You can see the full list of new features and updates below and the diff between 8.33.0 and 8.34.0 on GitHub. The following release notes are directly from the changelog:

v8.34.0

Inspiring

  • Added more inspiring quotes (92b7bde)

Added

  • Added WSREP communication link failure for lost connection detection (#36668)
  • Added "exclude-path" option to route:list command (#36619, 76e11ee)
  • Added Illuminate\Support\Str::remove() and Illuminate\Support\Stringable::remove() methods (#36639, 7b0259f, 20e2470)
  • Added Illuminate\Database\Eloquent\Relations\MorphPivot::getMorphType() (#36640, 7e08215)
  • Added assertion to verify type of key in JSON (#36638)
  • Added prohibited validation rule (#36667)
  • Added strict comparison to distinct validation rule (#36669)
  • Added Illuminate\Translation\FileLoader::getJsonPaths() (#36689)
  • Added Illuminate\Support\Testing\Fakes\EventFake::assertAttached() (#36690)
  • Added lazy() and lazyById() methods to Illuminate\Database\Concerns\BuildsQueries (#36699)

Fixed

  • Fixes the issue using cache:clear with PhpRedis and a clustered Redis instance. (#36665)
  • Fix replacing required :input with null on PHP 8.1 in Illuminate\Validation\Concerns\FormatsMessages::getDisplayableValue() (#36622)
  • Fixed artisan schema:dump error (#36698)

Changed

  • Adjust Fluent Assertions (#36620)
  • Added timestamp reference to schedule:work artisan command output (#36621)
  • Expect custom markdown mailable themes to be in mail subdirectory (#36673)
  • Throw exception when unable to create LockableFile (#36674)

Refactoring

  • Always prefer typesafe string comparisons (#36657)

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.