Errol Paleracio
Errol Paleracio

Reputation: 634

How do I send and process one to many request in laravel

I'm working with an inventory system and I'm in the part where the cashier adds items to be purchased. So the tables i'm working with in that particular module is sales and sale_items. So the relationship is 1 sale has many sale_items.

So my question is. How can I send a request in one go without using ajax. Currently I'm using ajax but my controller requires authentication. I turned off the authentication to make the ajax request work. Below is the sample request body that I wanna send without ajax.

sales{
   date_sold: 04/01/2019,
   discount: 2000,
   branch_id
   sales_item: 
   {
      product_id: 1,
      quantity: 20,
      unit_price: 200
   },
   {
      product_id: 2,
      quantity: 40,
      unit_price: 100
   },
   {
      product_id: 3,
      quantity: 50,
      unit_price: 300
   }
}

I want to insert these data to the sales and sales_item tables respectively. How do I process it in laravel?

Upvotes: 0

Views: 172

Answers (3)

Bachtiar Panjaitan
Bachtiar Panjaitan

Reputation: 415

if your problem is only authentication, why not use laravel passport to handle API authentication?.

this frontend without ajax.

<form action="{{route('your route')}}" method="post">
{{csrf_field()}}
<input type="date" name="date_sold">
<input type="integer" name="discount">
<select name="branch_id" id="">
 <option value=""></option>
 <option value=""></option>
</select>
<!--  sales item -->
<select name="product_id[]" id="">
 <option value=""></option>
 <option value=""></option>
</select>
<input type="number" name="quantity[]" id="">
<input type="number" name="unit_prize[]">
</form>

and on request, you will get sale_items as array data.

Upvotes: 0

Vildan Hakanaj
Vildan Hakanaj

Reputation: 1

You can create a new table that defines the relationship between the sale and the items. So you would have a sale_item_rel where it would contain the id of the sale and the id of the items. When you get the request assuming you are sending the ids of the item and the sale in an array. Then you just need to insert the id of the sale and the id of the item into the table. Also checking that the item exists.

Assuming this is what you meant Hope this helps.

Upvotes: 0

Jesus Erwin Suarez
Jesus Erwin Suarez

Reputation: 1585

Create a relationships between sales and sale_items and you may do like this code below in your controller.

$sale = App\Sale::Find($id);

$saleItems = collection([..]);

foreach($saleItems as $item)  { 
    $sale->saleItems()->create([
         'sale_id' => $item->sale_id, 
    ]);
}

Upvotes: 1

Related Questions