Laravel11+Livewire3报错Undefined array key 'title',无法读取数据库数据
使用PHP 8.3.13、Laravel 11.42.1与Livewire 3开发时,从数据库读取产品数据持续报错Undefined array key "title",执行dd($this->products)返回空数组,尝试过php artisan cache:clear、php artisan migrate及新建项目仍无法解决,目标是在视图中展示产品表所有数据。以下是代码问题分析及修复方案:
1. 模型类名与规范不匹配
问题:
模型文件命名为Product.php,但类名写成了Products,不符合Laravel「单数模型类名对应复数数据表」的规范,会导致框架无法正确识别数据表。同时Livewire组件中引入的是App\Models\Product,但调用时用了Products::all(),产生类引用错误。
修复:
修改app\Models\Product.php的类名为单数Product:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected $fillable = [ 'title', 'description', 'price', 'image' ]; // 若数据表名不是默认的products,可手动指定 // protected $table = 'products'; }
2. Livewire组件模型调用错误
问题:
Livewire组件中错误调用了不存在的Products::all(),导致无法读取数据,$products始终为空数组。
修复:
修改组件中的模型调用为正确的单数模型类:
<?php namespace App\Livewire; use Livewire\Component; use App\Models\Product; #[Layout('layouts.app')] class Products extends Component { public $products = []; public function mount() { $this->products = Product::all(); } public function render() { return view('livewire.products'); } }
3. Blade模板属性访问方式错误
问题:
视图中使用数组方式$product['title']访问模型属性,但Product::all()返回的是Eloquent集合,每个元素是模型对象,需用对象属性访问语法->。
修复:
修改product.blade.php中的属性访问代码:
<div> <table> <thead> <th>Title</th> <th>Deskripsi</th> <th>Price</th> <th>Action</th> </thead> <tbody class="bg-white divide-y divide-gray-200"> @foreach ($products as $product) <tr class="hover:bg-gray-50"> <td class="px-6 py-4 whitespace-nowrap"> <div class="text-sm text-gray-900">{{ $loop->iteration }}</div> </td> <td class="px-6 py-4 whitespace-nowrap"> <div class="text-sm text-gray-900">{{ $product->title }}</div> </td> <td class="px-6 py-4 whitespace-nowrap"> <div class="text-sm text-gray-900"> Rp{{ number_format($product->price, 0, ',', '.') }}</div> </td> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium"> </td> </tr> @endforeach </tbody> </table> </div>
4. 组件与视图文件名不匹配
问题:
Livewire组件类名为Products,默认对应视图文件livewire/products.blade.php,但你的视图文件名为product.blade.php(单数),会导致视图加载异常。
修复:
- 要么将视图文件重命名为
products.blade.php,保持与组件类名复数一致; - 要么修改组件的
render方法,指定正确的视图路径:
public function render() { return view('livewire.product'); }
5. 确认数据库存在数据
dd($this->products)返回空数组,可能是products表中没有数据。可通过以下方式添加测试数据:
- 执行
php artisan tinker,输入:Product::create(['title' => '测试产品', 'description' => '测试描述', 'price' => 100000, 'image' => 'test.jpg']); - 手动在数据库
products表中插入数据
内容的提问来源于stack exchange,提问作者Joshia Agrisa Anrhiely Luther

