Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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

Never Miss a Laravel Release 🚀

Sign up and get an email with each new Laravel release

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
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

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

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant 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

The latest

View all →
The Inertia v3 Beta is Here image

The Inertia v3 Beta is Here

Read article
Polyscope Is an Ai-First Dev Environment for Orchestrating Agents image

Polyscope Is an Ai-First Dev Environment for Orchestrating Agents

Read article
Filament v5.3.0 Released with Deferred Tab Badges and Column Manager Improvements image

Filament v5.3.0 Released with Deferred Tab Badges and Column Manager Improvements

Read article
Ward: A Security Scanner for Laravel image

Ward: A Security Scanner for Laravel

Read article
Kit: An Opinionated API Starter Kit for Laravel image

Kit: An Opinionated API Starter Kit for Laravel

Read article
Livewire v4.2.0 Released with Security Hardening and Laravel 13 Support image

Livewire v4.2.0 Released with Security Hardening and Laravel 13 Support

Read article