artyak's avatar

Laravel updateOrCreate don't update value

///del

0 likes
3 replies
flightsimmer668's avatar

@artyak The updateOrCreate may only be called on Eloquent models.

Perhaps it's just the way you've named them, but it doesn't seem to me that Tournament_matches and Tournament_teams are Eloquent models -- perhaps these are collections and not Eloquent models -- thus updateOrCreatewould not work.

flightsimmer668's avatar

I needed to make sure that Tournament_teams and Tournament_matches were indeed Eloquent models.

Looking at the documentation for updateOrCreate found at https://laravel.com/docs/7.x/eloquent#other-creation-methods, it looks like you need a second array containing the property and value to be updated. So, for example, if your intent is to update the league_name for a matching tournament_id, then it should be done like this:

$tournament = Tournament::updateOrCreate(
	['tournament_id' => $tournament_id], 
	['league_name' => $full_name]
);


Tournament_teams::updateOrCreate(
	[ 'tournaments_id' => $tournament->id ],
        [
            'team' => $team->name, 
            'slug' => $team->slug, 
            'logo' => $team->image_url,
            'team_id' => $team->id,
            'match_id' => $team->match_id ?? null
        ]
);

The link to the documentation also explains why your values are being saved (created) and not updated.

flightsimmer668's avatar

In your foreach loop for Tournament_teams you have a null coalesce for match_id.

foreach ($tournament_teams as $team) {
        Tournament_teams::updateOrCreate([
            ...
            'match_id' => $team->match_id ?? null
        ]);

    }

It might be worth doing a dump($team->match_id) on each iteration just to make sure that you are not getting null values here.

Please or to participate in this conversation.