I know using:
User::firstOrCreate(array('name' => $input['name'], 'email' => $input['email'], 'password' => $input['password']));
Checks whether the user exists first, if not it creates it, but how does it check? Does it check on all the params provided or is there a way to specifiy a specific param, e.g. can I just check that the email address exists, and not the name - as two users may have the same name but their email address needs to be unique.
firstOrCreate() checks for all the arguments to be present before it finds a match.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'abcd',
'lastName' => 'efgh',
'veristyName'=>'xyz',
]);
Then it check only the email
An update:
As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate
method now accepts an optional second array as an argument.
The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:
Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate
now has second parameter values
, which is being used for new record, but not for search
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
Source: Stackoverflow.com