Im trying to setup a polymorphic relationship but struggling. Here are my databases
public function up()
{
Schema::create('features', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->integer('order')->unsigned()->default(0);
$table->foreignId('featurer_id');
$table->string('featurer_type', 50);
$table->timestamps();
});
Schema::create('feature_section', function(Blueprint $table) {
$table->foreignId('feature_id');
$table->foreignId('section_id');
$table->timestamps();
});
}
Schema::create('sections', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->string('name', 50);
$table->timestamps();
});
Then in my models I have Section.php
class Section extends Model
{
use HasFactory;
/**
* Get the featured for the section .
*/
public function featured()
{
return $this->belongsToMany(Feature::class);
}
}
and Feature.php
class Feature extends Model
{
use HasFactory;
/**
* The relations to eager load on every query. I am adding shows here because I need to filter by dates for the search
*
* @var array
*/
protected $with = ['featureable'];
/**
* Get the section that has this featured
*/
public function features()
{
return $this->belongsToMany(Section::class);
}
/**
* Get the section that has this featured
*/
public function featureable()
{
return $this->morphTo();
}
}
However when I do
return Section::all()->load('featured');
I get
{
"id": 1,
"user_id": 1,
"name": "homepage",
"created_at": null,
"updated_at": null,
"featured": [
{
"id": 1,
"user_id": 1,
"name": "a",
"order": 0,
"featurer_id": 1,
"featurer_type": "App\Models\Curated\Community",
"created_at": null,
"updated_at": null,
"pivot": {
"section_id": 1,
"feature_id": 1
},
"featureable": null
},
{
"id": 2,
"user_id": 1,
"name": "x",
"order": 0,
"featurer_id": 67,
"featurer_type": "App\Models\Event",
"created_at": null,
"updated_at": null,
"pivot": {
"section_id": 1,
"feature_id": 2
},
"featureable": null
}
]
}
]
and it doesn't include the community or event model with the featured model, just leaves it null.
Thanks!