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 review blog posts (written by other users) before they get published on your WordPress blog?

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

What are the SPL Iterators in PHP?

How to reverse htmlentities() / What is the opposite of htmlentities()?

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

How do you launch the PHP interactive shell?

How to do comments in Blade files?

What are the SPL data structures

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to manually write your own pagination in PHP