There is no built-in way right now. Perhaps in Laravel 4.1, which was supposed to completely rewrite polymorphic relationships.
Add a type property to Image , then define where conditions for the relationship:
public function mugshot() { return $this->morphOne('Image', 'of')->where('type', 'mugshot'); } public function photos() { return $this->morphMany('Image', 'of')->where('type', 'photo'); }
Remember to set type to the Image you are creating. Or, as I did, hide this logic inside the model.
Here is my code (I am using PHP 5.4 with a short write array):
Picture
namespace SP\Models; class Image extends BaseModel { const MUGSHOT = 'mugshot'; const PHOTO = 'photo'; protected $hidden = ['type']; public function of() { return $this->morphTo(); } }
Person
namespace SP\Models; use SP\Models\Image; class Person extends BaseModel { public function mugshot() { return $this->morphOne('SP\Models\Image', 'of') ->where('type', Image::MUGSHOT); } public function photos() { return $this->morphMany('SP\Models\Image', 'of') ->where('type', Image::PHOTO); } public function saveMugshot($image) { $image->type = Image::MUGSHOT; $image->save(); $this->mugshot()->save($image); } public function savePhotos($images) { if(!is_array($images)) { $images = [$images]; } foreach($images as $image) { $image->type = Image::PHOTO; $image->save(); $this->photos()->save($image); } } }
Somewhere in the controller / service:
$person->savePhotos([$image1, $image2]);
source share