firstOrCreate() Not Inserting Model

Sometimes firstOrCreate() Not Inserting Model in laravel. There could be any reason for the method firstOrCreate() not working in your case. Basically the firstOrCreate() method creates the record if the record does not exist in the table else it updates the record.

Answers 1
  • Laravel firstOrCreate method to create a record if it not already exist in the table

    --PATH app\Http\Controllers\<YourController>.php
    Post::firstOrCreate(
        ['slug'=> $request->slug],
        ['title' => $request->title, 'body' => $request->body]
    );
    
    0

    firstOrCreate method is used to create a record if it does not already exist in the table in laravel. It has two parameters, conditions and fields and these parameters should be an array. It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new record after applying attributes passed in the second parameters including first parameter field and values. 

    This code snippet will create a new post record including title, body and slug fields in the post table if the record is not already exist with this particular slug.

  • Back to code snippet queries related laravel