trandall's avatar

Remove pivot table entries when deleting records

First post, apologies if this isn't in the correct location or if I'm not clear.

What I'm trying to do... When I go to delete a team, I want to delete any games associated to that team, and I want to delete the association between any players associated to those games (e.g. delete the records in game_player), but not delete the players. This is what I have so far:

    public function destroy(Team $team)
    {

$games = Game::where('team_id',$team->id)->get();

        $games->players->detach();
        
            $games->delete();

        $team->delete();

    }

The error I'm getting is "Method Illuminate\Database\Eloquent\Collection::players does not exist."

0 likes
8 replies
Talinon's avatar

This is because $games->players will return a collection of players, and that method does not exist on the collection. Try $games->players()->detach() instead.

trandall's avatar

of course. still somewhat new to laravel and that one seems to trip me up a lot. Thanks!

trandall's avatar

Actually... I did have the parenthesis. I manually made a correction to my post and accidentally deleted them.

So $games->players->detach(); produces Property [players] does not exist on this collection instance.

$games->players()->detach(); produces Method Illuminate\Database\Eloquent\Collection::players does not exist.

Any other thoughts?

Talinon's avatar

Within your Games model, do you have the return keyword for your players relationship?

public function players()
{

    return $this->hasMany(...);

}
trandall's avatar

Yes, sadly I do :(

in Games.php

    public function players()
    {

        return $this->belongsToMany(Player::class)->withPivot('position_id');

    }

if I try to change it to hasMany, I get this error:

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::withPivot()

Talinon's avatar
Talinon
Best Answer
Level 51

Using belongsToMany is correct, I was just typing out an example.

I think its because you are getting a collection of Games when you call get(), instead of a model instance.

You would probably be better off setting up an onDelete cascade on your table.

Or, I think this would work:

  public function destroy(Team $team)
    {

    Game::where('team_id',$team->id)->get()->each(function ($game) {

        $game->players()->deatch();
        $game->delete();

    });

        $team->delete();

    }
1 like
trandall's avatar

Yes! That did it! Thank you very much!

Please or to participate in this conversation.