Home > Mobile >  Laravel 9 - How to display the number of my products from my shopping basket?
Laravel 9 - How to display the number of my products from my shopping basket?

Time:09-20

I'm creating a shop on Laravel 9 and I would like to add a shopping basket with the number of products I have added on my 'paniers' SQL table.

I wrote this on my controller :

    public function AffichageBoutique()
    {
        $boutiques = Boutique::all();
        $nbr = Panier::where('iduser', session('iduser'))->get()->count();
        return view('boutique.Boutique')->with('boutiques', $boutiques)->with('paniers', $nbr);
    }

$nbr is the number of my products I have on my basket, for example -> 4.

I would like to display this number on my page like this, it's an animated basket =>

            <div >
            <figure>
                <img src="/img/icons/bell_icon.svg" alt="" >
                <figcaption>
                    <p>{{ $nbr }}</p>
                </figcaption>
            </figure>
        </div>

But I have this error : Undefined variable $nbr.

What's the problem ?? Thank you !

CodePudding user response:

return view('boutique.Boutique')->with('boutiques', $boutiques)->with('paniers', $nbr);

in your return you are passing the $nbr variable and renaming it as 'paniers', either you change the name to 'nbr' (->with('nbr', $nbr)) or in your html you call for $paniers

You can find more in Laravel official documentation

CodePudding user response:

Maybe try something like this:

public function AffichageBoutique() {
     $boutiques = Boutique::all();
     $nbr = Panier::query()
          ->where('iduser', session('iduser'))
          ->count(); //Just grab the count.
     
     return view('boutique.Boutique', [
         'boutiques' => $boutiques,
         'nbr' => $nbr
     ])
}

And then for your view:

<div >
     <figure>
          <img src="/img/icons/bell_icon.svg" alt="" >
          <figcaption>
               <span>({{ $nbr }})</span>
          </figcaption>
      </figure>
</div>

I'd also suggest returning "$nbr" as something more explicit, like, $user_panier_cart_total or $card_total maybe.

  • Related