As of Laravel 5.3 it's possible to do this in one step with firstOrCreate
using a second optional values
parameter used only if a new record is created, and not for the initial search. It's explained in the documentation as follows:
The firstOrCreate
method will attempt to locate a database record using the given column / value pairs. If the model cannot be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument.
Example
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
This returns the User
for the specified email if found, otherwise creates and returns a new user with the combined array of email
, firstName
, and lastName
.
This technique requires Mass Assignment to be set up, either using the fillable
or guarded
properties to dictate which fields may be passed into the create
call.
For this example the following would work (as a property of the User
class):
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['email', 'firstName', 'lastName'];