Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skaisser's avatar

First Or Create Result

Hey Guys!

Whe you use first or create function from eloquent, Is there a way to know if the data was persisted or located?

Example:

 $dadosPagamento = [
                    'pedidos_id' => $pedido->id,
                    'meio_pagamento' => 'Asaas',
                    'codigo_pagamento' => $idAsaas,
                    'valor' => $valor
                    ];
                    $pagamento = Pagamento::firstOrCreate($dadosPagamento);

I wanted to know if the item was created, if it was created i would update my slack channel, If it was only found i would ignore it.

Cheers!

0 likes
13 replies
Pendo's avatar

I guess you could check the increment ID number with the ID of the record that is being returned.

skaisser's avatar

Thank you @trs_uk Exactly what i was looking for, I knew laravel had this somewhere.

kabircse's avatar
Level 1

Use wasRecentlyCreated property as for checking if inserted now or exist.

        $product = Wish::firstOrCreate(['product_id'=>$product_id,'user_id'=>$user_id]);
        $product->save();
        if($product->wasRecentlyCreated){
        echo 'Created successfully';
    } else {
            echo 'Already exist';
        }
6 likes
jimbojjz's avatar

Sorry im new to Laravel but am I right in thinking $product->save() is not necessary here?

ejdelmonico's avatar

@jimbojjz If you read about firstOrCreate it is looking for the first record in the DB...if it doesn't find one...it creates a new one. So, to answer your question, yes most would save the new record.

jimbojjz's avatar

Im using it without save and its making the db insertion though.

2 likes
jekinney's avatar

Save is not needed and matter of fact you are creating then updating. (Updating nothing) but if it finds the record it requires the save() method I believe. I generally use findOrNew instead.

FindOrCreate is good for like a user's profile after a new user hits their profile page. If the profile doesn't exist it will create a new one with defaults and return that object.

Where as find or new will not create but return a find object or a new empty class ready to manipulate

1 like
jimbojjz's avatar

Yeah I had initially used firstOrNew() and might go back to it. I just was wondering if I was missing something obvious as I removed save() from firstOrCreate().

Thanks.

galironfydar's avatar

Or anyone wanted something to update the model if found. Then you can use Model::updateOrCreate($attributes, $values);

    User::updateOrCreate(
        ['email' => '[email protected]'], // Find by email
        ['first_name' => 'Jon', 'last_name' => 'Doe'] // Update or Create with these
    );

Please or to participate in this conversation.