Call to undefined method using Relation Manager Attach

Hi,

I have an Exercise model and each exercise can have some 'related exercises' where the relations are stored in a pivot table.

I'm trying to use a Filament Relation Manager to attach/detach related exercises in a table under the Exercise resource form.

The table populates as it should with the seeded related exercises. And I can detach related exercises too. So it feels like I've got things set up correctly.

But I have a problem attaching new related exercises.

I can click the Attach button from the form and the modal pops up with a searchable select field. But when I try to search, I get the error "Call to undefined method App\Models\Exercise::exercises()"

The Laravel error page actually correctly suggests the solution "Did you mean App\Models\Exercise::relatedExercises() ?" which I do want to use.

But my problem is, I can't figure out where to define the correct method, or even why it's looking for an "exercises()" method when it's not specified anywhere.

In Exercise.php model
public function relatedExercises(): BelongsToMany
    {
        return $this->belongsToMany(Exercise::class, 'related_exercises', 'exercise_id', 'related_exercise_id');
    }


In RelatedExercisesRelationManager.php
protected static string $relationship = 'relatedExercises';


In ExerciseResource.php
public static function getRelations(): array
    {
        return [
            RelationManagers\RelatedExercisesRelationManager::class,
        ];
    }


My two database tables look like this:
  • exercises-- id-- name
  • related_exercises-- exercise_id-- related_exercise_id
Any help would be very much appreciated.
Solution
@pboivin You're right, it turns out I did need the inverse relationship.

In Exercise.php model I added:
public function exercisesRelatedTo(): BelongsToMany
    {
        return $this->belongsToMany(Exercise::class, 'related_exercises', 'related_exercise_id', 'exercise_id');
    }


And in RelatedExercisesRelationManager.php I added
public function table(Table $table): Table
    {
        return $table
            ...
            ->inverseRelationship('exercisesRelatedTo');
    }


I'm not entirely sure why this is needed, but it works! I can now search and attach in the modal as expected.

Thank you for your help.
Was this page helpful?