The issue you're facing is that the relationship is only loading in one direction. To make it work both ways, you need to define the relationship on both ends of the model.
Here's how you can modify your Report model to establish a many-to-many relationship with itself:
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Report extends Model
{
public function related(): BelongsToMany
{
return $this->belongsToMany(
Report::class,
'reports_related',
'report_id',
'related_report_id'
)->withTimestamps();
}
public function relatedTo(): BelongsToMany
{
return $this->belongsToMany(
Report::class,
'reports_related',
'related_report_id',
'report_id'
)->withTimestamps();
}
}
By adding the relatedTo method, you can now access the related reports from the other end of the relationship.
To save the relationships, you can simplify your UpdateController.php code as follows:
$report->related()->sync($request->related_ids);
This will automatically handle deleting old relations and creating new ones based on the provided related_ids array.
Make sure to update your migration file to include the timestamps() method:
Schema::create('reports_related', function (Blueprint $table) {
$table->foreignId('report_id')->constrained()->cascadeOnUpdate()->cascadeOnDelete();
$table->foreignId('related_report_id')->constrained('reports')->cascadeOnUpdate()->cascadeOnDelete();
$table->timestamps();
});
With these changes, you should be able to establish a many-to-many relationship between reports in both directions.