It seems like there is a misunderstanding in how the polymorphic relationships are set up in your Eloquent models. The Ask model should not have a morphMany relationship to Activity, because Ask is not the parent in this polymorphic relation, it is the child. Instead, Ask should have a morphOne or morphMany relationship to Activity through the activitable method.
Here's how you can fix the relationships:
- Remove the
activitiesmethod from theAskmodel, as it is not needed. - Ensure that the
Activitymodel has themorphTorelationship correctly set up, which it does in your provided code. - When you are associating the
Askwith anEvent, you should create anActivityinstance and set theactivitablerelationship to theAsk.
Here's the corrected code:
// Event model stays the same
class Event extends Model
{
// ... existing code ...
public function activities()
{
return $this->morphMany(Activity::class, 'activitable');
}
}
// Ask model without the activities() method
class Ask extends Model
{
use HasFactory;
protected $fillable = ['description', 'shortdescription', 'status'];
// No activities() method needed here
}
// Activity model stays the same
class Activity extends Model
{
// ... existing code ...
public function activitable()
{
return $this->morphTo();
}
}
// Test method with corrections
public function test_creating_an_ask()
{
// ... existing code ...
// Create the ask
$ask = Ask::create([
'description' => 'Test Event Description',
'shortdescription' => 'Test Event Short Description',
'status' => 'active', // or any other status
]);
// Create an activity and associate it with the ask
$activity = new Activity();
$activity->activitable()->associate($ask);
$newEvent->activities()->save($activity);
// Assert that the Activity was associated with the ask and event
$this->assertEquals($newEvent->id, $activity->activitable->id);
$this->assertEquals(get_class($newEvent), $activity->activitable_type);
// Assert that the Activity was added to the database
$this->assertDatabaseHas('activities', [
'id' => $activity->id,
'activitable_id' => $ask->id,
'activitable_type' => get_class($ask),
'status' => 'active', // or any other status
]);
}
Make sure that your activities table has the correct columns for a polymorphic relationship: activitable_id and activitable_type. The activitable_id column should store the ID of the related model (in this case, the Ask ID), and the activitable_type should store the class name of the related model (in this case, 'App\Models\Ask').
Also, ensure that you have run the migrations to add these columns to the activities table if you haven't already.