Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The easiest way to insert multiple tables from one form

Tags:

laravel

in laravel i want to insert into two tables the data from one form.

my forms are:

<input type="text" name="name"class="form-control">
<input type="text" name="age"class="form-control">
<input type="text" name="sex"class="form-control">
<input type="text" name="location"class="form-control">

i want to insert the name, age, and sex to table details. and input location to table locations

location model belongsTo detail model.

how to insert them at the same time? and how to automatically match the id of detail with detail_id of location?

i have search but too difficult to follow. i wish there's an easy way to follow.

like image 410
Adriani Umar Avatar asked Oct 18 '22 09:10

Adriani Umar


1 Answers

You didn't show us your model relationships and what you have in your controller so far. But assuming your models are correctly related and your table field names are the same names as your form names, you could try this in your controller:

 public function store(Request $request)
  {
  $detail = new detail();
  $detail->name = $request->input("name");
  $detail->age = $request->input("age");
  $detail->sex = $request->input("sex");
  $detail->save();

 $location = new location();
 $location->detail_id = $detail->id;
 $location->location = $request->input("location");
 $location->save();
 }

hope this help.

like image 68
Daddi Al Amoudi Avatar answered Oct 21 '22 03:10

Daddi Al Amoudi