Conditionally Fail Queue Jobs While Throttling Exceptions in Laravel 12.20

Last updated on by

Conditionally Fail Queue Jobs While Throttling Exceptions in Laravel 12.20 image

Never Miss a Laravel Release 🚀

Sign up and get an email with each new Laravel release

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.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Tinkerwell logo

Tinkerwell

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

Tinkerwell
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
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
PhpStorm logo

PhpStorm

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

PhpStorm
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
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 $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
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
Lucky Media logo

Lucky Media

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

Lucky Media
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud

The latest

View all →
Turn PHP Attributes Into Docs With Signal image

Turn PHP Attributes Into Docs With Signal

Read article
USAIGE: Track Token Usage and Costs for Laravel AI SDK Requests image

USAIGE: Track Token Usage and Costs for Laravel AI SDK Requests

Read article
Help make Filament faster! image

Help make Filament faster!

Read article
Yammi Audit Log: Track Who Really Made a Change Across Jobs and Queues image

Yammi Audit Log: Track Who Really Made a Change Across Jobs and Queues

Read article
Route Metadata Support in Laravel 13.17 image

Route Metadata Support in Laravel 13.17

Read article
Ship AI with Laravel: Failover, Queues, and Middleware for AI Agents image

Ship AI with Laravel: Failover, Queues, and Middleware for AI Agents

Read article