Reputation: 1
i have a many-to-many relationship between Product and User models,I'm trying to instanciate one relationship between a user and a specific product Or updateit's column 'favoris' if it's already existing.
I'm not sure if im using the adequate methodes .
<?php
namespace App\Http\Controllers;
use App\Http\Middleware\Authenticate;
use App\Models\Product;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class StatisticsController extends Controller
{
public function favoris(Request $request){
$user=Auth::user();
$list_prods_fav_true=[];
$favs=$request->input('favoris');
Log::info($favs);
$list_favoris=collect();
$list_unfavoris=collect();
$message='';
try{
foreach ($favs as $fav) {
$prod= $fav['produit'];
try{
$product=Product::find($prod["id"]);
if(!$product){
$product=Product::create(
[
'id'=>$prod["id"],
'nom'=>$prod["nom"],
'description'=>$prod["description"],
'img'=>$prod["img"]
]
);}
$nbre_lignes_updated=$user->products()->updateExistingPivot(
$prod->id,['favoris'=>true]
);
if($nbre_lignes_updated===0){
Log::info('update '.$nbre_lignes_updated);
$user->products()->syncWithoutDetaching([$prod->id=>['favoris'=>true]]);
}
array_push($list_prods_fav_true,$prod['id']);
}
catch(Exception $e){
$message=$e;
}
/*
$product->updateExistingPivot($prod['id'],['favoris'=>true]);
*/
$list_prods_fav_false=$user->products->diff(Product::whereIn('id',$list_prods_fav_true)->get());
foreach($list_prods_fav_false as $prod){
$nbre_lignes_updated=$user->products()->updateExistingPivot(
$prod->id,['favoris'=>false]
);
if($nbre_lignes_updated===0){
Log::info('upadte '.$nbre_lignes_updated);
$user->products()->syncWithoutDetaching([$prod->id=>['favoris'=>false]]);
}
else{
Log::info('update',$nbre_lignes_updated);
}
}
$list_favoris=$user->products()->wherePivot('favoris',true)->get();
$list_unfavoris=$user->products()->wherePivot('favoris',false)->get();
}}
catch(Exception $e){
$message=$e;;
}
return response()->json([
'message'=>'liste des favoris est bien recue '. $message,
'liste des favoris'=>$list_favoris,
'liste des unfavoris'=>$list_unfavoris,
]);
}
}
the result is always an empty array for list_favoris ,that's when i added updateExistingPivot, before i used only syncWithoutDetaching and it creates up to 4 relashionship objects every time i add one product to favorite.
Upvotes: 0
Views: 24