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 not all arguments match, then a new instance of the model will be created.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value'])
with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.
The difference between firstOrCreate()
and firstOrNew()
:
firstOrCreate()
will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.firstOrNew()
will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save()
on the model). Otherwise it will give you the matched item.Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name
or some mandatory field), you should use firstOrNew()
. If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate()
.