Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Vishnu Damwala
Vishnu Damwala

Posted on

     

Laravel's firstOrCreate Model Method

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=[])
Enter fullscreen modeExit fullscreen mode
  • 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();
Enter fullscreen modeExit fullscreen mode

Example withfirstOrCreate()

$device=Device::firstOrCreate('uuid',request('uuid'));$device->operating_system=request('operatingSystem');$device->version=request('version');$device->save();
Enter fullscreen modeExit fullscreen mode

Read the complete post on our siteLaravel's firstOrCreate Model Method

Read others post on our siteMeshWorld

Happy 😄 coding

With ❤️ from 🇮🇳

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A human being currently living in India🇮🇳 on Earth.Founder of MeshWorld, a web geek, an industry experienced web developer & tutor/instructor currently lives in Surat City.
  • Location
    Surat, India
  • Joined

More fromVishnu Damwala

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp