I have two models Product and Raw Materials many to many relation the pivot table contains additional columns quantity and the cost. In view When the users select raw materials with quantity wanted the table should show the cost of this raw material with added quantity multiplied by initial quantity from raw Materials table The pivot table produit_raw_material contains:
- produit_id (foreign_id of Product Model)
- raw_material_id (foreign_id of RawMaterial Model)
- quantite (quantity)
- montant (cost)
raw_materials table contains:
- reference
- designation (name)
- qte_initial (inicial quantity of goods)
- qte_alert
- prix_achat (price)
- status
Once the user select the raw material and the quantity in specific product, i want to retrieve the initial cost from RawMaterial Table and multiply it with the quantity that the user added with map collection method.
Produit Model:
class Produit extends Model
{
use HasFactory;
protected $fillable = ['reference', 'designation', 'qte_a_produire', 'qte_fabrique',
'qte_restance', 'unite'
];
public function rawmaterials(){
return $this->belongsToMany('App\Models\RawMaterial')->withPivot(['quantite','montant']);
}
}
RawMaterial Model
class RawMaterial extends Model
{
use HasFactory;
public function produits(){
return $this->belongsToMany('App\Models\Produit');
}
}
View show.blade.php
<form action="{{route('admin.produits.sync', ['id'=>$produit->id])}}" method="post">
@csrf
<table>
@foreach ($rawall as $rawall)
<tr>
<td>
<input data-id="{{$rawall->id}}" type="checkbox" class="ingredient-enable">
</td>
<td>
{{$rawall->designation}}
</td>
<td>
<input data-id="{{$rawall->id}}"
type="text"
name="rawqte[{{$rawall->id}}]"
class="ingredient-amount form-control"
placeholder="Quantite"
disabled>
</td>
</tr>
@endforeach
</table>
<button type="submit" class="btn btn-info">Synchroniser</button>
</form>
ProduitController:
public function sync(Request $request, $id){
$produit = Produit::find($id);
//Quantity Input
$rawQte= $request->input('rawqte') ;
$rawQteKeys = array_keys($rawQte);
$prixAchats = RawMaterial::orderBy('id', 'asc')->whereIn('id', $rawQteKeys)->pluck('prix_achat')->toArray();
$rawqtes = collect($request->input('rawqte', []))->map(function($rawqte) use($prixAchats) {
foreach($prixAchats as $prixAchat){
$cost = $prixAchat * $rawqte;
}
return ['quantite'=>$rawqte, 'montant'=>$cost];
});
$produit->rawmaterials()->sync($rawqtes);