laraveleloquentlaravel-bladelaravel-5.8illuminate-container

How to output table data from controller to view?


I'm in the beginning stages of trying to make sense of Laravel and am having trouble displaying the 'illuminate collection object' passed to a blade from a controller.

My print_r is outputting "Illuminate\Support\Collection Object ( [items:protected] => Array ( ) ) 1" which I thought meant that it was seeing one item in the array (just one record in the table currently), but I'm hitting the @else statement so I'm guessing it's actually empty. I'm getting no errors, but I have not been able to display anything from $products despite $title outputting just fine.

public function shop(){
        $products = DB::table('products')->get();
        $data = array(
            'title'=>'Shop',
            'products' => $products
        );
        return view('pages.shop')->with($data);
    }
@section('content')
    <h1>{{$title}}</h1>
    {{ print_r($products) }}
    @if($products->count())
        <ul class="list-group">
            @foreach($products as $product)
                <li class="list-group-item">{{$product->title}}</li>
            @endforeach
        </ul>
    @else
        <p>No products</p>
    @endif
@endsection

Why is my array empty?


Solution

  • On your Controller:

    $title = 'Shop';
    $products = DB::table('products')->get();
    
    return view('pages.shop', compact('title', 'products');
    

    On your Blade:

    I would also suggest to put your unordered list tag <ul> outside of the loop then use @forelse for a cleaner code, like so:

    @section('content')
      <h1>{{$title}}</h1>
      <ul class="list-group">
        @forelse($products as $product)
           <li class="list-group-item">{{$product->title}}</li>        
        @empty
           <li class="list-group-item">No products</li>  
        @endforelse
      </ul>
    @endsection