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

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

What is an example of an object literal?

How to check if a (blade) view file exists

How to force SSL in Apache's .htaccess?

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

Force trailing slash (redirect if no trailing slash exists) in .htaccess

What is the loop variable in a @foreach loop in Blade?

What does PEAR stand for?

What is the max size, by default, of GET variables?

How to enable the rewrite engine in .htaccess?