[英]Can't display the values from my data base with Laravel Livewire
I'm using a Livewire component, this is my code:我正在使用 Livewire 组件,这是我的代码:
Search.php:搜索.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: 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>
My vegetable Model:我的菜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;
}
}
My problem is, every time im typing something in my search bar, I just have a No result appearing on my screen even tho i seeded my data base with some vegetables already.我的问题是,每次我在搜索栏中输入内容时,即使我已经在我的数据库中播种了一些蔬菜,我的屏幕上也只会出现“无结果”。 Why doesn't it show me for example Carrot when i type it?
为什么当我输入它时它不显示例如胡萝卜?
You're only pulling in your Vegetables once the function "updateQuery" has been called.一旦调用了 function“updateQuery”,您就只需要拉入您的蔬菜。 I'd recommend adding it to your render and setting
public $query;
我建议将它添加到您的渲染中并设置
public $query;
to an empty string, eg 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()
])
}
This way if the query is empty it will continue to show the vegetables, but once you begin to search it'll filter it using the where clause.这样,如果查询为空,它将继续显示蔬菜,但是一旦您开始搜索,它将使用 where 子句对其进行过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.