Search code examples
phpdatabaselaravelmany-to-manylaravel-5.3

Store data into a many to many table relashionchip Laravel


I need to create a method to write data to a relationship table. And I'm sending the data via get, and I need to store them in my table. Below is the code I wrote to you the moment.

public function store(Request $request){

        $campanha = Campanha::find($request->campanha);

        foreach ($request->chksintese as $key => $value) {
            $campanha->sinteses()->attach($value);

        }

        return redirect('sintese-campanha');
    }

My request comes this way:

array:2 [▼
  "campanha" => "26"
  "chksintese" => array:5 [▼
    0 => "92"
    1 => "86"
    2 => "1"
    3 => "9"
    4 => "13"
  ]
]

In my models I have the relationship methods:

public function sinteses(){
         return $this->belongsToMany(Sintese::class);
}

And

public function campanhas(){
        return $this->belongsToMany(Campanha::class);
}

I know this is pretty basic, but I'm starting now on laravel. I hope someone can help.

I`m gettin an error:

QueryException in Connection.php line 769:
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "campanha_sintese" does not exist
LINE 1: insert into "campanha_sintese" ("campanha_id", "sintese_id")...
^ (SQL: insert into "campanha_sintese" ("campanha_id", "sintese_id") values (31, 13))

My migration code for my relashionship table

 public function up()
{
    Schema::create('callcenter.campanha_sintese', function(Blueprint $table) {

        $table->integer('sintese_id')->unsigned;
        $table->foreign('sintese_id')->references('cod_sintese_conversa')->on('crm.sintese_conversa');

        $table->integer('campanha_id')->unsigned;
        $table->foreign('campanha_id')->references('id_campanha')->on('callcenter.campanha_new');

        $table->timestamps();
    });
}

Solution

  • Pass your table to your relationships so Laravel know where to look for the relationship.

    public function sinteses(){
        return $this->belongsToMany(Sintese::class, "callcenter.campanha_sintese");
    }
    
    public function campanhas(){
        return $this->belongsToMany(Campanha::class, "callcenter.campanha_sintese");
    }
    

    You may also need to add primary and foreign key in your relationship. Check the guide on Laravel how to add those keys. Pretty easy.