Create a record if not exist in laravel

Updated at 05-Apr-2021, By samar

Create a record if not exist in laravel

In this session, we are going to try to solve the "Create a record if not exist in laravel" puzzle by using the computer language.

  • 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]
    );
    

    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.

  • Create a new record if not exist in laravel using create method

    --PATH app\Http\Controllers\<YourController>.php
    $user = User::where('username', $request->username)->first();
    
    if(!$user){
        $user = User::create([
            'email' => $request->email,
            'username' => $request->username,
            'password' => bcrypt($request->password)
        ]);
    }
    

    This code snippet helps you to find the record if any already exists with this particular username and check that if the user with this particular username is not already exist then it creates a new user using the create() method.

Back to code snippet queries related laravel