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 pick what array_intersect function to use in PHP?

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

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

How to set up an alias to map one directory to another destination

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

What are generators in PHP, and how do they compare to arrays?

Point all requests to one PHP file

How to get table column names from a database table in Eloquent?

What is the difference between empty(), isset(), != null, is_null() in PHP

How to block IPv6 IP addresses in .htaccess