Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to get data from database and print it using foreach loop but I have undefined variable error.

In my web.php I have

Route::get('/ShowProducts' , 'ProductController@ShowProducts');

This is my code in controller

function ShowProducts(){
    $show = ProductModel::where('ID')->get();

    $show->Product_Name;
    $show->Count;
    $show->Price;

    return view('profile');
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
880 views
Welcome To Ask or Share your Answers For Others

1 Answer

You don't have $id argument on your function, if you want to list all products, use this:

function ShowProducts() {
   $products = ProductModel::all();
   return view('profile', ['products' => $products]);
}

and on your blade:

@foreach($products as $prod)
    <h3 class="product-title">
        <a href="product.html">{{$prod->Product_Name}}</a>
    </h3>
@endforeach

If you want to show a single product, add a new route with {id}:

Route::get('/ShowProducts/{id}' , 'ProductController@ShowProduct');

and on your controller:

function ShowProduct($id) {
   $product = ProductModel::findOrFail($id);
   return view('profile', ['product' => $product]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...