Ahsan
Ahsan

Reputation: 1359

Laravel: how to check if input value exists in table

I am saving data to a table with following store method.

public function store(Request $request)
    {
        foreach ($request->admin_id as $key=>$val){
            $adminbillings = AdminBilling::create([
                'month' => $request->month,
                'rate' => $request->rate[$key],
                'admin_id' => $val,
            ]);          
        }

        return redirect('/');
    }

Now, I want to check if any of the input values is already existed in the table before storing them. If a row in the table already contains all 3 same inputs, it should do nothing, otherwise store the inputs. It would be something like

if  
    $requested->month     does not exist in month     column || 
    $requested->rate      does not exist in rate      column || 
    $requested->admin_id  does not exist in admin_id  column 
then 
    save

Please help me. I am using Laravel 5.4.

Thank you

Upvotes: 1

Views: 3901

Answers (1)

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5186

There is a Laravel method to help you out called firstOrCreate see https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Builder.php#L356

How will you use

AdminBilling::firstOrCreate([
  'month' => $request->month,
  'rate' => $request->rate[$key],
  'admin_id' => $val,
]);

Explanation

if you see the source code it does a where & first if it finds that it just returns that

    if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
    }

else it creates a new row with the given array & returns the model

    return tap($this->newModelInstance($attributes + $values), function ($instance) {
        $instance->save();
    });

Tips

When you use a firstOrCreate you should always only unique one then update with the rest of the data e.g

                Course::firstOrCreate([
                    'isbn' => (string) $isbn,
                ])->update([
                    'title' => $title,
                    'url' => 'URL',
                    'date_published' => $datePublished
                ]);

Here ISBN is unique for me so I called firstOrCreate with $isbn then I just updated the row with the rest of the data

Upvotes: 1

Related Questions