I expose this topic already treated in different threads that in my case generates an error that I cannot solve.
I have a many-to-many relationship with the Client and Factor models . What I want to do is store in the pivot table client_factor two extra fields, apart from the id of the two related tables ( factor_id, client_id ), which will be pointsfactor (points assigned) and gender (gender).
Client Model
public function clientsFactors()
{
return $this->belongsToMany(Factor::class, 'client_factor')->withPivot('pointsfactor', 'gender');
}
Model Factor
public function factorsClients()
{
return $this->belongsToMany(Client::class, 'client_factor')->withPivot('pointsfactor', 'gender');
}
Client_factor Pivot Table Migration
public function up()
{
Schema::create(
'client_factor', function (Blueprint $table) {
$table->id();
$table->foreignId('factor_id')->constrained('factors')->onDelete('cascade');
$table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
$table->integer('pointsfactor')->default(0);
$table->string('gender')->nullable();
$table->timestamps();
}
);
}
I collect the data to insert in the pivot table from a form that returns 3 arrays ( factor_id[], pointsfactor[], gender[] ).
ArrayFactor_id
array:15 [▼
0 => "1"
1 => "2"
2 => "3"
3 => "4"
4 => "5"
5 => "6"
6 => "7"
7 => "8"
8 => "9"
9 => "10"
10 => "11"
11 => "12"
12 => "13"
13 => "14"
14 => "15"
]
Array Factor
array:15 [▼
0 => "5"
1 => "5"
2 => "15"
3 => "5"
4 => "25"
5 => "5"
6 => "5"
7 => "10"
8 => "5"
9 => "8"
10 => "5"
11 => "5"
12 => "5"
13 => "25"
14 => "5"
]
ArrayGender
array:15 [▼
0 => "NEUTRO"
1 => "NEUTRO"
2 => "FEMENINO"
3 => "MASCULINO"
4 => "MASCULINO"
5 => "NEUTRO"
6 => "NEUTRO"
7 => "MASCULINO"
8 => "NEUTRO"
9 => "FEMENINO"
10 => "FEMENINO"
11 => "FEMENINO"
12 => "NEUTRO"
13 => "NEUTRO"
14 => "NEUTRO"
]
To save the data in the pivot table, I pass the array with the id of the factors and the arrays with the data of the additional columns to the sync method.
$factores = $request->factor_id;
$puntos = $request->pointsfactor;
$genero = $request->gender;
$client->clientsFactors()->sync(
[
$factores => [
'pointsfactor' => implode(",", $puntos),
'gender' => implode(",", $genero)
]
]
);
But it generates the following error: Error message: Illegal offset type
What am I doing wrong? How should I insert the additional fields in the pivot table?
Thank you...
What is wrong is that the variable $factors has an array, and not a value. You can organize your array so that you have something like this:
and once with the arranged array you can do: