Mastering Laravel's Latest: New Session Directives and Advanced Testing Tools
Overview
Prerequisites
To get the most out of these features, you should be comfortable with basic
Key Libraries & Tools
- Laravel10.37/10.38: The core framework providing these new helpers.
- Blade: Laravel's powerful templating engine.
- PHPUnit: The testing framework used to validate route redirections and job chains.
Code Walkthrough
Simplified Session Display
Previously, displaying a flash message required manual checks via the session helper. The new @session directive automates this and provides a local $value variable.
@session('status')
<div class="alert alert-success">
{{ $value }}
</div>
@endsession
Improved Route Testing
When testing redirects, we often need to specify where a user originated. The fromRoute method replaces the generic from method, allowing you to use route names instead of hardcoded URLs.
$response = $this->actingAs($user)
->fromRoute('news.edit', ['news' => $news])
->put(route('news.update', $news), $data);
$response->assertRedirect();
Asserting Chained Jobs via Closures
You can now inspect the specific properties of a chained job using a closure, ensuring that the correct data passes through the queue.
Bus::fake();
// Run the logic...
Bus::assertChained([
function (ReleasePodcast $job) {
return $job->podcastId === 1;
}
]);
Syntax Notes
The @session directive is a specialized conditional. It only renders its content if the specified key exists in the session, automatically injecting the value into a scoped $value variable. In testing, the assertValidationError method now accepts an array of strings, allowing you to verify that multiple validation rules (like string and min:5) failed simultaneously for a single input field.
Tips & Gotchas
When using the new closure-based job assertions, always type-hint the job class in the closure signature. This ensures @session directive, remember that it specifically looks for flashed data; it won't replace standard persistent session logic for long-term data storage.
