I'm having some problems getting a Polymorphic Relation to work in Laravel
Tables
Vacations
id
name
Posts
id
name
Images
id
type_id
type
Images.type_id
links to posts.id
or vacations.id
Images.type
is either post
or vacation
Posts and Vacations can have many images but each image belongs to only 1 Post or Vacation.
Vacation Model
namespace App;
use App\Vacation;
class Vacation extends Model
{
public function images()
{
return $this->morphMany('App\Image', 'imageable', 'type', 'type_id');
}
}
Image Model
namespace App;
use App\Image;
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
When I run this, I get an empty array but there are matching records.
$vacation = Vacation::find(1);
dd($vacation->images);
I can see Laravel is trying to run:
select * from `images` where `images`.`type_id` = 1
and `images`.`type_id` is not null
and `images`.`type` = App\Vacation
When I run this "raw" and replace "App\Vacation"
with vacation
then I get my results.
Is it normal it's passing the namespaced class name to the raw sql query?
I've tried changing the Images.type
value from plural to singular but it still fails.
What am I doing wrong?
EDIT: this is Laravel 5.4, the most recent version afaik.