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

Published on by

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

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

image
No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project.

Visit No Compromises
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
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

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
Bacancy - Staff Augmentation logo

Bacancy - Staff Augmentation

Leave your web app development hustles to the leading IT Staff Augmentation Service Providers. Choose from an extensive pool of 1050+ developers and give yourself the sigh of success you deserve with Bacancy. Get In Touch Today!

Bacancy - Staff Augmentation
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

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

Rector

The latest

View all →
Add Architecture Tests to Saloon API Integrations with Lawman image

Add Architecture Tests to Saloon API Integrations with Lawman

Read article
Protect Routes with JWT Tokens Using This Package for Laravel image

Protect Routes with JWT Tokens Using This Package for Laravel

Read article
Increment a Rate Limiter by a Custom Amount in Laravel 10.46 image

Increment a Rate Limiter by a Custom Amount in Laravel 10.46

Read article
Add Kanban Boards to Your Laravel App in Seconds image

Add Kanban Boards to Your Laravel App in Seconds

Read article
October CMS v3.6 Ships Today, Full of New Features image

October CMS v3.6 Ships Today, Full of New Features

Read article
Laracon EU Videos are now out image

Laracon EU Videos are now out

Read article