I have 3 tables, Cars, Flats and Shops. Each table has its photos. Photos is stored in database. I want to use only one table for photos, I don\'t want to create Photos table fo
You can make use of Eloquent's Polymorphic relationships. The example in the Laravel Documentation actually showcases setting up a common images table for multiple models, so that should point you in the right direction. In your case something your models would look something like this:
class Photo extends Eloquent {
public function imageable()
{
return $this->morphTo();
}
}
class Car extends Eloquent {
public function photos()
{
return $this->morphMany('Photo', 'imageable');
}
}
class Flat extends Eloquent {
public function photos()
{
return $this->morphMany('Photo', 'imageable');
}
}
class Shop extends Eloquent {
public function photos()
{
return $this->morphMany('Photo', 'imageable');
}
}
And you could access the photos for, let's say a given Flat
, like this:
Flat::find($id)->photos;
For this to work you'd also need to add 2 additional columns to your photos
table:
imageable_id: integer <-- This will be the ID of the model
imageable_type: string <-- This will be the model's class name (Car/Flat/Shop)