1

I am using Laravel 5. I am facing a problem while creating a new Member - system finds an existing entry and crashes.

Is there any Laravel/PHP way to verify if Member already exists before creation and update just updated_at timestamp?

$member = new Member(['group' => 1, 'user_id' => 1]);
$member->save();

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 'MEMBER_GROUP';

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
Michaela
  • 31
  • 5
  • 1
    use `Member::updateOrCreate([$findProps, $updateProps])`. – Flame Dec 16 '19 at 15:00
  • Does this answer your question? [laravel updateOrCreate method](https://stackoverflow.com/questions/42695943/laravel-updateorcreate-method) – Nico Haase Dec 16 '19 at 15:29

1 Answers1

0

You want to look into Laravel's updateOrCreate method. So you will do something like:

Member::updateOrCreate(['group' => 1, 'user_id' => 1], []);

This will try to find a user with user_id 1 and group 1, if it doesn't find it, it will create it for you otherwise it will just update it.

In your case, I have given the update array as [] as you will not need to update anything if the match is found.

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64