DEV Community

Salamah-Hbr
Salamah-Hbr

Posted on

Attempt to read property "produits"on null

I'm using Laravel 8 and, I want to add to the wishlist after I click add, I get an error. I believe that the way I want to access the product is wrong.
this is my controller

public function addToFavorie($id)
{
    $user = Auth::user();
    $product = produit::find($id);

    if (!$product || !$user) {
        abort(404);
    }

    // I believe this is the part responsible for the error
    $favorie = $user->favorie;
    $favprds = $favorie->produits;
    //

    for ($i = 0; $i < count($favprds); $i++) {
        if ($favprds[$i]->id == $id)
            return redirect()->back()
                ->with('error', 'produit deja dans votre favorie');
    }
    $favorie->produits()->attach($product->id);

    return redirect()->back()->with('info', 'produit ajoute a votre favorie');
}
Enter fullscreen mode Exit fullscreen mode

i've tried this in my controller it return page 404

$user = Auth::user()->favorie;
$product = produit::find($id);

if (!$product || !$user) {
    abort(404);
}

$favprds = $favorie->produits;
Enter fullscreen mode Exit fullscreen mode

this is my model i tried to change belongsToMany to hasMany same problem

public function user()
{
    return $this->belongsTo("App\Models\User");
}

public function produits()
{
    return $this->belongsToMany('App\Models\Produit', 'produits_favories');
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)