1

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

Ahsan
  • 907
  • 3
  • 9
  • 27
  • Perhaps make unique key for the columns in question and let RDBMS handle that, in your app just catch the exception. https://stackoverflow.com/questions/635937/how-do-i-specify-unique-constraint-for-multiple-columns-in-mysql – Kyslik Aug 09 '17 at 18:12
  • I am not sure, because I want to store values if at least one of the inputs is unique to its own column. If one input is unique, other two can have many values in their own columns. – Ahsan Aug 09 '17 at 18:35
  • use NULL-able fields, those are treated as non-unique https://stackoverflow.com/questions/3712222/does-mysql-ignore-null-values-on-unique-constraints ; I see it probably wont work for you, sorry. – Kyslik Aug 09 '17 at 18:40

1 Answers1

1

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

ARIF MAHMUD RANA
  • 4,466
  • 3
  • 26
  • 49