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.
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."
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();
}
Please or to participate in this conversation.