Search code examples
laravellaravel-9

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


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 class="icon-wrapper">
            <figure>
                <img src="/img/icons/bell_icon.svg" alt="" class="bell-icon">
                <figcaption>
                    <p>{{ $nbr }}</p>
                </figcaption>
            </figure>
        </div>

But I have this error : Undefined variable $nbr.

What's the problem ?? Thank you !


Solution

  • 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 class="icon-wrapper">
         <figure>
              <img src="/img/icons/bell_icon.svg" alt="" class="bell-icon">
              <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.