Laravel Community Tools by Tighten

Tag "relationships" tricks

27 tricks
You can chain eager loading to avoid N+1 problem. Suppose you have 3 tables. customer[id, email], pos[id, serial_number] and restaurant[id, name, customer_id, pos_id] so restaurant table can act like a pivot table and it also have some value attribute. So now we can call customer from pos table via chaining eager loading.
milon 11 years ago 20313
Laravel has many choices for performing a query, sometimes it could be confusing, I hope this list help you to clear any doubts. If you know other way please show it in comments for add it.
luismec90 11 years ago 13939
I recently figured out that you can specify the columns that you want to select from an eager loaded relationship in Eloquent. I thought others might find this useful as I couldn't find much about this online!
stidges 11 years ago 42010
I've used this technique to check if I have called any `->with()` or other relations loaded on a model. I had a need for this since I have a lot of methods that require relation data in order to generate an appended property on the model. For example, if I want to pull all of the recent Posts of an Author and I want to store it on the model as `posts_this_month`, I would need to have Posts relation loaded. I want to force myself to eager load that data before I try to access it, otherwise I could run into an n+1 problem.
chadwithuh... 11 years ago 31139
Sometimes you might want to delete/update a whole lot of items that are related to a model when a record under that model is deleted from the database. This could be useful for various scenarios when there is a lot of processing that needs to be done upon model deletion. Laravel provides model events that you can use in that case.
msurguy 11 years ago 41183
It's possible to add condition to your model's relationships... Help me to use Eloquent with a legacy database..
Matt 12 years ago 9043
When saving/updating a model you might want to get a JSON response that includes some relationship data as well.
m4nuC 12 years ago 11136
Combining Model Observers and Cache Tags for very simple but elegant automatic cache flushing on Eloquent Model updates. Can handle both a Model and its Relations easily!
nik-418 12 years ago 30263
I spent a good hour trying to figure out why my Eloquent relationship wasn't working when I found out it was because of the difference between `$model->relationship->value` and `$model->relationship()->value`.
chadwithuh... 12 years ago 109822