News

Conditionally Fail Queue Jobs While Throttling Exceptions in Laravel 12.20

Published
Conditionally Fail Queue Jobs While Throttling Exceptions in Laravel 12.20 image

Release updates

Never miss a Laravel release

Get an email whenever a new Laravel release lands.

The Laravel team released v12.20.0 with the ability to fail while throttling queue exceptions, a Queue Facade fakeFor method, a Context::remember() method, the ability to customize Collection pluck() with a callback, and more:

Remember Context

Ben Askew contributed Context remember() and rememberHidden() functions, which will add the result of the provided closure function to the context if not already present, and always return the result:

// Before
if (Context::has('user-permissions')) {
$permissions = Context::get('user-permissions');
} else {
$permissions = auth()->user()->permissions;
Context::set('user-permissions', $permissions);
}
 
// After
$permissions = Context::remember('user-permissions', fn() => auth()->user()->permissions)

See Pull Request #56156 for details.

"Doesn't Start/End With" String Methods

Balboa Codes contributed doesntStartWith() and doesntEndWith() string methods to the Str and Stringable classes, which are the opposite of startsWith() and endsWith(). You can compare the value against another string or an array of strings:

use Illuminate\Support\Str;
 
Str::doesntEndWith('This is my name', 'dog'); // true
Str::doesntEndWith('This is my name', ['name', 'foo']); // false
 
Str::doesntStartWith('This is my name', 'That'); // true
Str::doesntStartWith('This is my name', ['This', 'That', 'There']); // false

See Pull Request #56168 for details. See the Strings documentation for more usage examples.

Add failWhen() Method to the ThrottlesExceptions Queue Middleware

Michael Dzjaparidze contributed a failWhen() method to the ThrottlesExceptions middleware:

Currently, this middleware only allows for deleting the job when a specific exception is thrown. There are occasions were you would want to mark the job as failed instead. For instance: in the context of a job chain it may be desirable to fail a job when an exception is thrown so that the chain stops executing.

Here's an example:

public function middleware(): array
{
return [
(new ThrottlesExceptions(2, 10 * 60))
->deleteWhen(CustomerDeletedException::class)
->failWhen(fn (\Throwable $e) => /* ... */)
];
}

See Pull Request #56180 for details. Additionally, the Queues documentation provides more information on using the ThrottlesException middleware.

Add fakeFor() and fakeExceptFor() Methods to the Queue Facade

Punyapal Shah contributed new fake methods to the Queue facade that follow the same pattern used by the Event facade.

// Before: Fake affects the entire test
Queue::fake();
// ... test code ...
// Manual cleanup required
 
// After: Fake is automatically scoped
Queue::fakeFor(function () {
Queue::push(new ProcessPayment);
Queue::assertPushed(ProcessPayment::class);
}); // Original queue automatically restored
 
// Selective job faking
// Allow critical jobs to be queued normally, fake others
Queue::fakeExceptFor(function () {
Queue::push(new CriticalSystemJob); // Actually queued
Queue::push(new EmailNotification); // Faked
 
Queue::assertNotPushed(CriticalSystemJob::class);
Queue::assertPushed(EmailNotification::class);
}, [CriticalSystemJob::class]);

See Pull Request #56149 for details.

Add JsonSerializable Interface to the Uri Class

@devajmeireles added the JsonSerializable interface to ensure the Uri class is converted property to JSON.

// Given
Route::get('/testing', function () {
return User::first()->only('id', 'url');
});
 
 
/* Before {"id": 1, "url": {}} */
 
/* After {"id": 1, "url": "https://sanford.biz/..."} */

See Pull Request #56097 for details.

Make the Fluent class Iterable

Volodya Kurshudyan introduced the Iterable contract to the Fluent class, which addresses a small paper cut when using Fluent with loops:

// Need to call toArray() to iterate
foreach ($user->settings->toArray() as $key => $value) {
//
}
 
// Now, the `settings` property is iterable in Laravel 12.20
foreach ($user->settings as $key => $value) {
//
}

See Pull Request #56218 for details.

Add collection() Method to the Config Repository

Kennedy Tedesco contributed a collection() method to return a collection instance from the Config repository:

// Before
collect(Config::array('my_file.my_key'));
 
// After
Config::collection('my_file.my_key');

See Pull Request #56200 for details.

Add Closure Support to the Collection pluck() Method

Ralph J. Smit contributed an update to the pluck() method to allow customizations to the keys and values returned:

This PR adds closure support to the $key/$value parameters of the pluck() methods. Very often I have that I almost can use pluck(), but I cannot because I need to make a slight modification to e.g. the key or value. I then need to solve this with mapWithKeys(), but that repeats the id and makes it way more verbose if you only just want to apply some formatting to the key and/or value.

After this PR, you can now do the following:

Country::get()
->pluck(fn (Country $country) => "{$country->flag} {$country->name}", 'id')

See Pull Request #56188 for details.

Context Blade Directive

Martin Bean contributed a @context Blade directive to determine if a context value exists:

@context('canonical')
<link href="{{ $value }}" rel="canonical">
@endcontext

See Pull Request #56146 for details.

Release notes

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

v12.20.0

Paul Redmond photo

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

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
Validate and Convert HEIC Images in Laravel image

Validate and Convert HEIC Images in Laravel

Read article
Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues image

Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues

Read article
Reject Unexpected Array Keys with Laravel Validation image

Reject Unexpected Array Keys with Laravel Validation

Read article
Major performance improvements & security patches for Filament v4.12 and v5.7! image

Major performance improvements & security patches for Filament v4.12 and v5.7!

Read article
Laravel Boost Project Rules: Teach Agents Your Conventions image

Laravel Boost Project Rules: Teach Agents Your Conventions

Read article
Extract an Image's Dominant Color in Laravel image

Extract an Image's Dominant Color in Laravel

Read article