大家好!
我有收藏的小問題。我從來沒有處理過這些。我想在我的歡迎刀片上顯示一個集合,但有一個問題。我的收藏不在控制器中,收藏的位置在 App/Repositories/xyz.php 和一個函式中。我如何將此功能傳遞給控制器??并在歡迎刀片上顯示它?
應用程式/存盤庫/xyz.php
public function getcars(): Collection
{
return collect([
new Car(...)
)];
控制器
public function __invoke(): View
{
return view('welcome', ['cars' => collect([
new Car() ------> I would like to put datas from xyz.php repo here
new Car()
new Car()
....
我想顯示的welcome.blade檔案
<div class="car-list">
<h2>{{ $title }}</h2>
@foreach($cars as $car)
<x-car :car="$car" />
@endforeach
</div>
uj5u.com熱心網友回復:
我相信從您的控制器檔案中,您可以通過如下__construct()方法創建存盤庫的物件屬性:
protected MyRepository $myRepository;
public function __construct(MyRepository $myRepository)
{
$this->myRepository = $myRepository;
}
然后,您可以$this->myRepository從那里呼叫的方法,例如獲取記錄等。然后您可以將結果傳遞給您的視圖。
uj5u.com熱心網友回復:
您可以通過多種方式做到這一點:
創建新實體
use App\repositories\Xyz;
public function __invoke(): View
{
$repo = new Xyz();
return view('welcome')->with('cars', $repo->getcars());
}
從容器中拉取 repo
use App\repositories\Xyz;
public function __invoke(): View
{
$repo = app(Xyz::class);
return view('welcome')->with('cars', $repo->getcars());
}
使用依賴注入從容器中決議它
use App\repositories\Xyz;
protected Xyz $repo;
public function construct(Xyz $xyz): View
{
$this->repo = $xyz;
}
public function __invoke(): View
{
return view('welcome')->with('cars', $this->repo->getcars());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/317418.html
上一篇:我的洗掉功能|方法無法在LaravelVuejs中洗掉
下一篇:檢查欄位
