Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Eloquent firstOrCreate method error

I try create new Model instance with Model::firstOrCreate, and i get error SQLSTATE[42S22]: Column not found.

My code snippet:


    $date = date("Y-m-d H:i:s");
    $order = 
    Order::firstOrCreate([
       ['name' => 'John'],
       [
           'type' => 'foo',
           'start' => $date,
       ]
    ]);

The code above will return an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'John' in 'where clause' (SQL: select * from `orders` where (`John` is null and `foo` = 2022-09-20 15:15:54) and `orders`.`deleted_at` is null limit 1)

My attention has been drawn next piece: select * from `orders` where (`John` is null and ... Eloquent substituted the value – John as a search column in the query, and I expected it to be a key name.

This official documentation about this method

What’s my mistake?

Screenshot
enter image description here

>Solution :

You have one extra pair of [].

Try like this:

$order = Order::firstOrCreate(
    ['name' => 'John'],
    ['type' => 'foo','start' => $date]
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading