While working on an application, you might have a need, initially to search from the table for an instance. And if it does not exists you need to explicitly create a new record and save in the table. Laravel provides a methodfirstOrCreate()
which comes handy, that performs both actions, searching or creating new and return that instance. So that you can just start working with it. This method is worth using.
In this article, we will see an example offirstOrCreate()
, a similar one likefirstOrNew()( that retrieves the first instance if it exists or creates a new model instance without saving actually in the table).
firstOrCreate()
ThefirstOrCreate()
method helps to find the firstmodel that matches the specified constraints orcreate a new model instance one if does not exists with the matching constraints.
Syntax
Model::firstOrCreate(array$attributes=[],array$values=[])
- It gets the first record matching the attributes or create a new one
- It searches the model with the matching attributes that are passed as the first parameter
- If a matching model is not found, it creates and saves a new Model after applying any key-value pair passed as the second parameter
Example withoutfirstOrCreate()
$uuid=request('uuid');$device=Device::where('uuid',$uuid)->first();if($device===null){$device=newDevice(['uuid'=>$uuid]);}$device->operating_system=request('operatingSystem');$device->version=request('version');$device->save();
Example withfirstOrCreate()
$device=Device::firstOrCreate('uuid',request('uuid'));$device->operating_system=request('operatingSystem');$device->version=request('version');$device->save();
Read the complete post on our siteLaravel's firstOrCreate Model Method
Read others post on our siteMeshWorld
Happy 😄 coding
With ❤️ from 🇮🇳
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse