4,000 emails/month for free | Mailtrap sends real emails now!

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
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
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 →
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article