Laravel 11.3: Clean Code Helpers and Attribute Handling

Laravel////2 min read

Elegant Job Handling with Attributes

Queued jobs often rely on model instances, but database state is fluid. When a job attempts to process a model that was deleted by a preceding process, traditionally throws a ModelNotFoundException. While we previously could define a public $deleteWhenMissingModels = true; property to silently discard these orphaned jobs, it lacked IDE support and felt like a workaround.

introduces the DeleteWhenMissingModels PHP attribute. By applying this directly to the class, you gain full auto-completion and a cleaner syntax. It signals the queue worker to automatically delete the job if the underlying model is gone, preventing your logs from filling up with avoidable errors.

Atomic Context Management with Pull

The new Context feature just became more versatile. We often need to retrieve a value and immediately wipe it to ensure it doesn't leak into subsequent logs or processes. Instead of manually calling get and then forget, you can now use the pull method. This returns the value—such as a user's locale or a tracing ID—and removes it from the current context in one transaction. It mirrors the behavior we've grown to love in collections and sessions, bringing much-needed consistency to the framework.

Simplifying Session Logic

Checking for multiple session keys used to involve messy conditional logic or multiple has calls. The addition of hasAny for sessions solves this. By passing an array of keys, you can verify if at least one of them exists. It’s a small change that significantly reduces the noise in your controllers, especially when handling optional user data or multi-step form progress.

Reliable Model Attribute Verification

Strict mode is a fantastic tool for catching bugs, but it makes checking for optional attributes tricky. If you try to access a non-existent property on a model in strict mode, throws an exception. Even array_key_exists fails us here because it doesn't see virtual accessors.

The new hasAttribute method is the definitive solution. It safely checks the underlying attributes array and accounts for those custom virtual accessors you've defined. It provides a safe way to probe your models without risking a crash, ensuring your code remains robust even as your data structures evolve.

Topic DensityMention share of the most discussed topics · 9 mentions across 8 distinct topics
22%· software
11%· software
11%· people
11%· people
11%· software
Other topics
33%
End of Article
Source video
Laravel 11.3: Clean Code Helpers and Attribute Handling

Delete When Missing Model, Context Pull, Attribute Has & More

Watch

Laravel // 7:19

The official YouTube channel of Laravel, the clean stack for Artisans and agents. We will update you on what's new in the world of Laravel, from the framework to our products Cloud, Forge, and Nightwatch.

Who and what they mention most
2 min read0%
2 min read