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

Inquisitive's avatar

Laravel firstOrCreate always creating new models

I am using dhtmlx file uploader, and here, it is uploading multiple files simultaneously, however, it is sending request for each file upload.

On this request, the firstOrCreate is always creating a new one. Here, are the images of two data created

https://ibb.co/FV94QL0 https://ibb.co/y896RcK

And, here is my code:

            $iSLog = ISectionLog::firstOrCreate(
                [
                    "inspection_section_id" => $section_id,
                    "inspection_log_id" => $inspectionLog->id,
                    'auth_user_group_id' => Auth::User()->userGroup->id
                ],
                [
                    "auth_user_id" => Auth::id()
                ]
            );
0 likes
6 replies
LaryAI's avatar
Level 58

It looks like you are missing a unique identifier in your firstOrCreate query. The firstOrCreate method will always create a new model if it can't find a match for the query. You need to add a unique identifier to the query, such as an id or slug field, so that the query can find the existing model.

For example:

$iSLog = ISectionLog::firstOrCreate(
    [
        "inspection_section_id" => $section_id,
        "inspection_log_id" => $inspectionLog->id,
        'auth_user_group_id' => Auth::User()->userGroup->id,
        'unique_identifier' => $unique_identifier
    ],
    [
        "auth_user_id" => Auth::id()
    ]
);
tykus's avatar

How simultaneous is it... firstOrCreate is potentially a two-step process - read for existing records and write to create a new record; if the first write has not been completed before the second request is handled, then there is no record to find, i.e.

Request 1    Request 2
Read
              Read
Write              
              Write     
Inquisitive's avatar

@tykus any idea to handle this situation, this is probably what I am facing. Instead of uploading 2 files, i uploaded 4 files, however on this case only 3 records got created, may be on 4th time the record was already created and finds the id, so it didn't create for that one.

tykus's avatar

@Inquisitive you could look at locking the table; but I would suggest you should instead queue the jobs so you can run them synchronously.

Inquisitive's avatar
Inquisitive
OP
Best Answer
Level 9

@tykus thank you for the suggestion. However, i make changes on front side, instead i send all files in single request.

Please or to participate in this conversation.