How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

Laravel: How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

You can use the very useful firstOrCreate() to try and find a row, and create it if it doesn't exist.

  1. // Retrieve flight by name, or create it if it doesn't exist...
  2. $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
  3.  
  4. // Retrieve flight by name, or create it with the name and delayed attributes...
  5. $flight = App\Flight::firstOrCreate(
  6.     ['name' => 'Flight 10'], ['delayed' => 1]
  7. );
  8.  
  9. // Retrieve by name, or instantiate...
  10. $flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
  11.  
  12. // Retrieve by name, or instantiate with the name and delayed attributes...
  13. $flight = App\Flight::firstOrNew(
  14.     ['name' => 'Flight 10'], ['delayed' => 1]
  15. );

There is also the firstOrNew which works in the same way, however it will provide an unsaved object (i.e. you will have the model object returned from the method call, but it won't be saved in the DB). There is also the updateOrCreate if you need to update models, or create it if none exist.

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to add the CSRF (Cross-site request forgery) token in Laravel?

What are the SPL Iterators in PHP?

How to check if a string contains a certain substring?

How to find the intersection (same values) from two arrays?

How to change the order that migrations happen?

How to check if a user is logged in, inside a blade file?

How to install and use optipng on Linux CentOS

How to replace whitespace with a single space

Why should you update APP_URL from from http://localhost?

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?