mardi 4 septembre 2018

if there is already '1' in the database, database won't accept another '1'. It will only accept '0'

I have this column is_default which accepts 1 or 0 depending if the 'Default' checkbox is checked or not.

My create.blade.php

<div class="form-check disabled">
  <label class="form-check-label">
    <input class="form-check-input" type="hidden" value='0' name="is_default">
    <input class="form-check-input" type="checkbox" value='1' name="is_default">
   Default Variant
  </label>
</div>

My VariantsController@store:

    DB::transaction(function() use (
        $request){
        $variant = Variant::firstorCreate([
            //some more code here
            'is_default'        => $request->is_default
        ]);

    }); 

In my variants table, I have a product_id which is a foreign key to products table. and I have the is_default column. Now, A Product, can have many Variants but there should only be one default variant per product.

So it's something like, (if the checkbox is checked) $checkdefault = Variant::where('product_id',$product)...find if there is a '1' in is_default and if there is no '1'then the database will save it, else it will save a zero and return a splash that says "there should only be one default variant"

I don't know if my explanation explains it well, but I appreciate any help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire