mardi 29 décembre 2015

Laravel 5. findOrNew for relationships

Just wondering if it is possible that some kind of findOrNew for relationships exist in Eloquent (in case if relationship do not exist attach new model instance)?

What that mean: Lets say that we have devices and specifications tables. Device belongs to specification. Specification_id is an FK (Know that is not best approach, but I have something like this left by previous programmer). Under id 11 we have device that do not have specification but we have to display that for user anyway.

$device = Device::find(11);
echo $device->specification->cpu;

In this case it will throw an error because specification will be null - it do not exist for device with id 11.

Know that I could check first if it exist but there a a lot of similar lines and app is pretty big. I need to move it from Kohana to Laravel. It works in Kohana because empty object is loaded then and 2nd line just return null. For Laravel I can just check if relationship exist and load new model then but I am curios if maybe there is any other and better way?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire