Monday, March 6, 2017

Storing Foreign Key values from 2 tables Laravel

I have 3 models - user, order & retailer I have created a form for the user to make an order. The order form has two select boxes. first one is select user which has all the user IDs the second is select retailer which has all the retailer IDs I then have a textbox to enter amount of the order.

On submitting the form i get the following error. SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (shop.orders, CONSTRAINT orders_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into orders (total, updated_at, created_at) values (10, 2017-03-06 10:22:43, 2017-03-06 10:22:43))

Can someone help me understand how i can store the foreign key values from the Users table, Retailers table into the Orders table?

my store method:

$data = \Input::only("name", "retailer", "total");
    $order = new Order($data);
    $order->save();
    return redirect("orders");

The create order form:

{!! Form::open(array("url"=>"orders", "class"=>"form-horizontal")) !!}

    <div class="form-group">
        {!! Form::label("name", "Select User", array("class"=>"col-md-2")) !!}
        <div class="col-md-10"> 
        {!! Form::select('id', $users, null, ['class' => 'form-control']) !!}
        </div>
    </div>

    <div class="form-group">
        {!! Form::label("retailer", "Select Retailer", array("class"=>"col-md-2")) !!}
        <div class="col-md-10"> 
        {!! Form::select('id', $retailers, null, ['class' => 'form-control']) !!}
        </div>
    </div>

    <div class="form-group">
        {!! Form::label("total", "Enter total", array("class"=>"col-md-2")) !!}
        <div class="col-md-10"> 
        {!! Form::text("total","",array("placeholder"=>"Enter total", "class="=>"form-control")) !!}
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-2"> {!! Form::submit('Order', array("class"=>"btn btn-primary","id"=>"btn")) !!} </div>
        <div class="col-md-10"><a href="" class="btn btn-success">Back..</a></div>
    </div>


    {!! Form::close() !!}



via Jay240692

Advertisement