I\'m trying to set up polymorphic relationships in Laravel 4 so that I can have one Image class which handles everything related to uploads, unlinks and so on, then have it used
No built-in way right now. Maybe in Laravel 4.1 that's supposed to bring a complete rewrite of polymorphic relations.
Add a type
property to Image
, then define where
conditions on the relations:
public function mugshot() {
return $this->morphOne('Image', 'of')->where('type', 'mugshot');
}
public function photos() {
return $this->morphMany('Image', 'of')->where('type', 'photo');
}
Don't forget to set type
on Image
s you create.
Or, like I did bellow, hide that logic inside the model.
Here's my code (I'm using PHP 5.4 with short array notation):
Image:
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 a controller/service:
$person->savePhotos([$image1, $image2]);