![](/img/trans.png)
[英]Can't display the values from my data base with Laravel Livewire
[英]Can't display the values from my data base with Laravel Livewire
我正在使用 Livewire 組件,這是我的代碼:
搜索.php:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;
class Search extends Component
{
public $query;
public $vegetables;
public function mount()
{
$this->resetQuery();
}
public function resetQuery()
{
$this->vegetables = [];
}
public function updateQuery()
{
$this->vegetables = Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray();
}
public function render()
{
return view('livewire.search');
}
}
search.blade.php:
<div class="searchcomponent">
<h1>Search</h1>
<input wire:model="query" type="text" placeholder="Rechercher...">
@if(!empty($query))
<ul>
@if(!empty($vegetables))
<div class="vegetables">
@foreach($vegetables as $vegetable)
<li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
@endforeach
</div>
@else
<li>No result</li>
@endif
</ul>
@endif
</div>
我的菜Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Vegetable extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = ['name'];
public function recipes(){
return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
}
public function getName($id) {
return $this->name;
}
}
我的問題是,每次我在搜索欄中輸入內容時,即使我已經在我的數據庫中播種了一些蔬菜,我的屏幕上也只會出現“無結果”。 為什么當我輸入它時它不顯示例如胡蘿卜?
一旦調用了 function“updateQuery”,您就只需要拉入您的蔬菜。 我建議將它添加到您的渲染中並設置public $query;
到一個空字符串,例如public $query = '';
if ($this->query != null) {
return view('livewire.search', [
'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
]);
} else {
return view('livewire.search', [
'vegetables' => Vegetable::all()->toArray()
])
}
這樣,如果查詢為空,它將繼續顯示蔬菜,但是一旦您開始搜索,它將使用 where 子句對其進行過濾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.