0

Let me explain what i try to achieve. lets say i have 20 car types for example sport car or family car etc, and 5 cars for example porsche.

When i create a car i have the option to check multiple car types at the same time that belongs to the car and than save it.

I have done some homework and it looks like using a pivot table is the way to go for this inside laravel.

I have this method inside my cars model:

public function types()
{
    return $this->belongsToMany('types', 'car_types');
}

And this method inside my types model:

public function cars()
{
    return $this->belongsToMany('Car');
}

My tables looks like this:

cars
- id
- name
- created_at
- updated_at

types
- id
- name
- created_at
- updated_at

car_types
- car_id
- type_id

What im trying to do inside my controller is:

    $car = new Car();
    Car::create( Input::except('types') );

    foreach(Input::get('types') as $type)
    {
      $car->types()->associate($type);
      $car->save();
    } 

This is giving me the following error:
Call to undefined method Illuminate\Database\Query\Builder::associate()

I hope someone can help me out with this.

Thanks in advance.

yinshiro
  • 159
  • 1
  • 13

1 Answers1

0

Well you are almost there. You're right that the two models, Car and Type are in a many to many relation.

In your models you have code that says:

return $this->belongsToMany('types', 'car_types');

and

return $this->belongsToMany('Car');

Error #1:

In the types() method of the Car model as the first parameter you should pass the name of the model, and not the name of the table. So you should change that to something like:

return $this->belongsToMany('Type', 'car_types');

Error #2

In your Car model you're defining the pivot table as car_types, but the pivot definition is missing from the Type model. Either remove , 'car_types' from the types() method in Car model and rename your pivot table to simply car_type, or add , 'car_types' to your cars() method in Type model.

Error #3

Once all the model stuff is set up correctly, you could do in your controller this:

$car = new Car();
$car->name = Input::get('car_name_form_field_name_attribute');
$car->save();

$types = Input::get('types');

$car->types()->sync($types);

Error #4

I'm not sure if this is just a copy/paste error, but your pivot table seems to be missing a primary key field. Every table needs a primary key field, so your car_types table should look something like this:

car_types

  • id
  • car_id
  • type_id

You could also use attach() instead of sync(). More about the difference between these two here

Please try out this code and let us know if it works out.

Community
  • 1
  • 1
Томица Кораћ
  • 2,542
  • 7
  • 35
  • 57
  • Thanks! There was one thing i needed to change and that was making a variable of Car::create( Input::except('types') ); and use that one for attaching the types. thanks alot for helping me out! – yinshiro Jan 23 '15 at 12:11