Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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.

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 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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
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 →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article