2

Suppose I have the following create code

$User = User::firstOrNew(
  array(
    'username' => $args['username'],
    'phone_no' => $args['phone_no']
  ),
  array(
    'otherDetails' => 'here',
  )
);

$User->save();

if (!$User->wasRecentlyCreated) {
  // code to check which field has same record in db    
}

After confirming that the insertion was not able to push through because an existing record has been fetched, is there any way I can find out which of either username or phone_no has the same data in the User table? Without using another where lookup in the model. Thanks.

rhanmiano
  • 23
  • 3
  • Since `username` and `phone_no` are in the first array of `firstOrNew`, the answer is both. If a record exists in your database with the same `username`/`phone_no` pair; then it is returned for you and you can access it as `$User`. – leek Jun 25 '20 at 15:27
  • This can help https://stackoverflow.com/a/21009418/4575350 – STA Jun 25 '20 at 15:28
  • Hi @leek, does that mean that the first argument of `frstOrNew` will work something like `WHERE username = ? AND phone_no = ?`. How about if we want to know if either of the fields already existed? Thank you, I'm new to Laravel - eloquent and its docs. – rhanmiano Jun 25 '20 at 23:57
  • @rhanmiano Correct. To do what you're asking, you are better off just querying `WHERE username = ? OR phone_no = ?`. If no record is returned, then you can proceed with creating one. – leek Aug 03 '20 at 03:51

0 Answers0