Auto-Apply Conditions in Laravel Relationships
45sThis tip solves a common pain point for Laravel developers, making it highly shareable and educational.
▶ Play Clip"Delivers exactly what the title promises — a concise, actionable Laravel tip with no fluff."
This video demonstrates a Laravel Eloquent tip: using a separate method with a condition for relationships, and the withAttributes() function to automatically apply that condition when creating related models.
You can define a relationship method with a where condition, and it will be automatically applied when accessing the relationship.
When creating related models, the condition is not automatically applied, so you must manually set the attribute.
The withAttributes() function applies the same condition automatically when creating related models, eliminating manual steps.
What function automatically applies a where condition when creating related models in Laravel?
withAttributes()
00:26
What is the benefit of using withAttributes() over manually setting the attribute?
It automatically applies the condition, so you don't need to manually set the attribute.
00:26
Separate Method with Condition
Shows how to define a relationship with a condition that is automatically applied when accessing the relationship.
withAttributes() for Creation
Introduces a function that applies the same condition when creating related models, saving manual steps.
00:26[00:00] When defining eloquent relationships, you may provide a separate method with condition. And then if you do user with that method, that where condition would be automatically applied.
[00:12] But also, there is a similar trick for creating related objects. The problem with this approach, if you do user feature post create, you can do that, but then you need to provide featured manually, because that condition wouldn't work.
[00:26] So did you know there is a function called with attributes? that would do the same wear condition as I showed previously, but also would allow you to do something like this. User feature posts, you provide only the title, and then featured would
[00:42] be automatically applied as well. For more Laravel tips and longer tutorials, subscribe to my channel Laravel Daily.
⚡ Saved you time reading this? Transcribe any YouTube video for free — no signup needed.