如何使用索引方法在 Laravel 中显示资源列表



我用Laravel资源创建了一个customerController。现在我想使用index()方法显示数据库中的客户列表,当我访问customer/index路由时它不起作用。但是,如果使用show()方法并访问customer/show路线,则可以完美运行。

为什么这样做,我如何获得index()方法来执行此操作?

class CustomerController extends Controller
{
public function index()
{
$customers = Customer::all();
return view('customer')->with('customers' , $customers);
}
public function show($id)
{
// adding the code in the index() method here makes the code run
// as expected
}
}

客户刀片.php

<ul>
@foreach($customers as $customer)
<li>{{$customer->name}}</li>
@endforeach
</ul>

路线/网络.php

Route::resource('customer' , 'CustomerController');

我希望输出为:

.sucre
.hameed
.micheal

我刚刚学会了如何在Laravel 8上使用资源。 您使用的是哪个版本? 在控制台上运行php artisan route:list以查看每个可用路由及其名称。

要通过索引函数查看所有客户,请执行以下操作:

public function index()
{
$customers = Customer::all();
return view('customer', [
'customers' => $customers
]);
}

现在只需在浏览器上访问您的customer.blade.php文件即可。

PS:不要忘记@foreach

@foreach ($customers as $customer)
{{ $customer->attribute }}
@endforeach

希望这可能是有用的。

最新更新