【发布时间】:2023-03-18 12:23:01
【问题描述】:
所以,我对 Laravel 很陌生,我想要实现的是将一些字符串从我的数据显示到页面。我正在使用 Eloquent 模型,但我无法弄清楚我在这里做错了什么。我在下面附上了我的一些代码。我希望我说得够清楚。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
class ProductsController extends Controller
{
public function index()
{
$products = Product::all();
return view('products.index')->with('products', $products);
}
这是我希望显示数据的位置。
@extends ('layouts.app')
@section ('content')
<div class="container-fluid">
<h1>Products</h1>
@if(count($products) > 1 )
@foreach ($products as $product)
<div class="well">
<h3>{{$product->prod_name}}</h3>
</div>
@endforeach
@else
<p>No product found</p>
@endif
</div>
@endsection
更新:问题出在我的循环逻辑上 由于我的数据库中只有一项,我的循环应该是 >= 1 而不是 > 1
@if(count($products) >= 1 )
@foreach ($products as $product)
<div class="well">
<h3>{{$product->prod_name}}</h3>
</div>
@endforeach
@else
<p>No product found</p>
@endif
【问题讨论】:
-
有什么错误吗?或者您面临的确切问题是什么?请在帖子中提及。
-
请复制实际代码而不是代码图像。它有助于 SEO、可读性和可用性。
-
你可以试试@if($products->count() > 1) 看看是否有什么不同。如果做不到这一点,请回显 $products->count(),以确认您确实有一些产品。
-
@Flame 嗨,对不起!我现在用实际代码而不是图片更新了帖子。
-
@Aashishgaba 问题是我无法遍历表以获取数据并将其显示在视图页面上。