Add following trait to your project and append it to your model class as a trait. This is helpful, because this adds functionality to use multiple pivots. Probably someone can clean this up a little and improve on it ;)
namespace App\Traits;
trait AppTraits
{
/**
* Create pivot array from given values
*
* @param array $entities
* @param array $pivots
* @return array combined $pivots
*/
public function combinePivot($entities, $pivots = [])
{
// Set array
$pivotArray = [];
// Loop through all pivot attributes
foreach ($pivots as $pivot => $value) {
// Combine them to pivot array
$pivotArray += [$pivot => $value];
}
// Get the total of arrays we need to fill
$total = count($entities);
// Make filler array
$filler = array_fill(0, $total, $pivotArray);
// Combine and return filler pivot array with data
return array_combine($entities, $filler);
}
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
use Traits\AppTraits;
// ...
}
Usage:
// Get id's
$entities = [1, 2, 3];
// Create pivots
$pivots = [
'price' => 634,
'name' => 'Example name',
];
// Combine the ids and pivots
$combination = $model->combinePivot($entities, $pivots);
// Sync the combination with the related model / pivot
$model->relation()->sync($combination);