Skip to content
Advertisement

Tag: eloquent

Laravel Eloquent – Attach vs Sync

What is the difference between attach() and sync() in Laravel 4’s Eloquent ORM? I’ve tried to look around but couldn’t find anything! Answer attach(): Insert related models when working with many-to-many relations No array parameter is expected Example: sync(): Similar to the attach() method, the sync() method is used to attach related models. However, the main differences are: sync() accepts

Laravel Check If Related Model Exists

I have an Eloquent model which has a related model: When I create the model, it does not necessarily have a related model. When I update it, I might add an option, or not. So I need to check if the related model exists, to either update it, or create it, respectively: Where <related_model_exists> is the code I am looking

Laravel Eloquent setting a default value for a model relation?

I have two models: This works fine, I can call $product->defaultPhoto->thumb and $product->defaultPhoto->full and get the path to the related image, and get all photos using $product->photos and looping through the values. The problem arises when the product does not have a photo, I can’t seem to figure out a way to set a default value for such a scenario.

Get previous attribute value in Eloquent model event

Is there a way to see the old/previous value of a model’s attribute in its saving or updating event? eg. Is something like the following possible: Answer Ok, I found this quite by chance, as it’s not in the documentation at present… There is a getOriginal() method available which returns an array of the original attribute values: Be careful, prior

Advertisement