Mastering Laravel 12.13: Named Queued Closures and Testing Redirects
Overview
assertRedirectBack, simplifies how we verify controller behavior after validation failures or form submissions.
Prerequisites
To follow this guide, you should be comfortable with:
- PHP 8.2+ syntax and basic closure usage.
- Laravel's queue system and job dispatching.
- Writing feature tests using Pest or PHPUnit.
Key Libraries & Tools
- Laravel 12.13: The framework version containing these updates.
- Queue Workers: The backend process that executes dispatched jobs.
- Laravel Testing Suite: The built-in tools for making HTTP requests and asserting responses.
Code Walkthrough: Named Queued Closures
Previously, dispatching a closure looked like this:
dispatch(function () {
// Some logic here
});
In your queue monitoring logs, this would simply show up as Closure. If you had ten different closures running, you couldn't distinguish between them. Now, you can provide a string name as the first argument to the dispatch method to identify the task.
// Assigning a specific name for visibility
dispatch('create-user-job', function () {
User::create(['name' => 'Dev Harper']);
});
When you check your queue worker logs or a dashboard like Laravel Horizon, you will now see create-user-job instead of a generic closure tag.
Code Walkthrough: Assert Redirect Back
Testing that a user is sent back to a form after a failed submission used to require knowing the exact URI they came from. You would typically use from($url)->post($target)->assertRedirect($url).
public function test_contact_form_validation_redirects_back()
{
$response = $this->from(route('contact.view'))
->post(route('contact.store'), []);
// The new, cleaner way
$response->assertRedirectBack();
}
This method automatically checks that the redirect destination matches the Referer header of the request, keeping your tests concise and focused on the intent rather than the specific URL.
Syntax Notes
- Method Overloading: The
dispatchhelper now intelligently handles both the name string and the closure. - Fluent Assertions: Like other Laraveltest methods,
assertRedirectBackcan be chained directly onto the response object.
Tips & Gotchas
- Name Uniqueness: Use descriptive names for closures to avoid confusion in high-traffic queues.
- State Management: Remember that closures are serialized. Avoid passing massive objects or resources (like database connections) into the
useclause of the closure.
