0

I have three tables: restaurant_location, cuisine_restaurant_location and cuisines.

There is a list of all cuisines in my cuisines table. I have all the details of the restaurant in my restaurant_location table. A restaurant can have many cuisines so I made a table cuisine_restaurant_location in which there are two columns cuisine_id and restaurant_id. I have created a belongs to many relation in my restaurant_location model.

restaurant_location model

public function cuisines()
{
    return $this->belongsToMany(Cuisine::class, 'cuisine_restaurant_location', 'restaurant_id', 'cuisine_id');
}

I have a form in which all the details of the restaurant along with cuisines is supposed to be added. Right now I am adding all the details of the restaurant. Now the question is how can I insert the cuisines in "cuisine_restaurant_location".

Controller

$rest = new restaurant_location;
$rest->name = $request->input('name');
$rest->description = $request->input('desc');
$rest->save();
$cuisine = new cuisine_restaurant_location
$cuisine_lists = $request->input('cuisines');
foreach ($cuisine_lists as $cuisine_list) {
    $cuisine->name = $cuisine_list;
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Haris Khan
  • 335
  • 5
  • 20

2 Answers2

1

You can use the sync and attach methods, described in the Many to many section of the eloquent documentation, for that:

$rest->cuisines()->attach([$cuisineIds])

Where cuisineIds is the list of ids of the cuisines you want to relate. The difference between sync and attach is that sync will remove all id's not present on the array of ids you are passing.

namelivia
  • 2,657
  • 1
  • 21
  • 24
  • I have a list of cuisine ids which i want to insert with the restaurant id. I use this $rest->cuisines()->attach(['cuisine_id'=>$cuisine_ids]); which result the error (`cuisine_id`, `location_id`, `0`, `1`) values (cuisine_id, 30, 1, 2)). ) column not found. can you tell me how to fix this ?? – Haris Khan Apr 04 '19 at 14:23
  • You should directly insert ids as a plain array, not an key-value array, like: `$cuisineIds = [1,2,3]` – namelivia Apr 04 '19 at 14:25
  • it is still adding a column 0. Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `cuisine_restaurant_location` (`cuisine_id`, `restaurant_id`, `0`) values (0, 31, 1)). – Haris Khan Apr 04 '19 at 14:30
  • Can you dump your `$cuisine_ids` array before attaching and post the result here? If you just want to attach the cuisine with ids 1 and 2 the array should be like `[1, 2]` – namelivia Apr 04 '19 at 14:39
0

Try sync() method:

$h = [];
if (isset($input["cuisine_id"])) {
    $h = $input["cuisine_id"];
}
$restaurant_location->cuisines()->sync($h);
Manisha
  • 70
  • 8