Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Laravel雄辩模型显示数据库中的数据_Laravel_Eloquent - Fatal编程技术网

使用Laravel雄辩模型显示数据库中的数据

使用Laravel雄辩模型显示数据库中的数据,laravel,eloquent,Laravel,Eloquent,所以,我对Laravel很陌生,我试图实现的是在页面上显示数据中的一些字符串。我用的是雄辩的模型,我不知道我做错了什么。我在下面附上了我的一些代码。我希望我说得够清楚 <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Product; class ProductsController extends Controller { public function index()

所以,我对Laravel很陌生,我试图实现的是在页面上显示数据中的一些字符串。我用的是雄辩的模型,我不知道我做错了什么。我在下面附上了我的一些代码。我希望我说得够清楚

<?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);
    }
而不是with(),也许视图::共享可以工作

$products = Product::all();
View::share('$products',$products);
return view('products.index');
别忘了从Facades导入View类。把这个放在第页的开头

use Illuminate\Support\Facades\View;

让我们修复您的代码并使用正确的方法

<?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', compact('products'));
    }

请注意我是如何使用
isEmpty
,它检查集合(此处从Eloquent获得)是否为空。

是否有错误?或者你面临的确切问题是什么?请在帖子中提及。请复制实际代码,而不是代码的图像。它有助于搜索引擎优化、可读性和可用性。你能试试@if($products->count()>1)看看这有什么不同吗。否则,请echo$products->count(),确认您确实有一些产品。@Flame嗨,对不起!我现在用实际的代码而不是图片更新了这篇文章。@Aashishgaba问题是我无法通过表格循环获取数据并将其显示在视图页面上。您倾向于使用view:share()当您想使数据对所有视图都可用时,我认为这不会有任何区别谢谢,我现在可以通过修复循环部分来修复代码,但是我很欣赏关于如何解决这个问题的良好实践。
use Illuminate\Support\Facades\View;
<?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', compact('products'));
    }
@extends('layouts.app')

@section('content')
    <div class="container-fluid">
        <h1>Products</h1>

        @if(!$products->isEmpty())
            @foreach($products as $product)
                <div class="well">
                    <h3>{{ $product->prod_name }}</h3>
                </div>
            @endforeach
        @else
            <p>No products found.</p>
        @endif
    </div>
@endsection