Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
881 views
in Technique[技术] by (71.8m points)

Laravel undefined variable issue

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

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

1 Reply

0 votes
by (71.8m points)

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]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...