提问者:小点点

搜索栏不工作使用laravel livewire


这是livewire的代码,每当我运行这段代码时,它都不会显示我正在使用Laravel7和livewire进行这种方法。

用于控制器

<?php
namespace App\Http\Livewire;
use App\Models\brands;
use Livewire\Component;

class SearchBar extends Component
{
    
    public $searchTerm;

    public function render()
    {
        $searchTerm = '%'.$this->searchTerm.'%';
        return view('livewire.search-bar', [
            'users' => brands::where('Name', 'like', $searchTerm)->get()
        ]);
    }
}

查看

<div>
    <input type="text" placeholder="Search users..." wire:model='searchTerm'/>

    <ul>
        @foreach($users as $user)
            <li>{{ $user->Website }}</li>
        @endforeach
    </ul>
</div>

共2个答案

匿名用户

我认为您的问题是,您正在搜索品牌模型中的“名称”,其中数据库列通常是小写的,因此您需要使用“名称”来代替。除非使用大写字母命名列,否则需要使用小写字母。下面是我将如何格式化Livewire组件。

<?php

namespace App\Http\Livewire;

use App\Models\Brands;
use Livewire\Component;

class SearchBar extends Component
{
    
    public $searchTerm;

    public function render() {
        return view('livewire.search-bar', [
            'users' => $this->users,
        ]);
    }

    public function getUsersProperty() {
        $query = Brands::query()
            ->when($this->searchTerm, fn($query) => $query->where('name', 'like', '%'.$this->searchTerm.'%'))
            ->get()

        return $query;
    }
}

我将隔离该函数,以便实际将品牌检索到另一个函数,这样就不会使渲染方法混乱。请注意,我没有声明public$users变量。如果不在组件中声明变量,Livewire将搜索getVariableNameProperty()函数并调用该函数。因此,在每次渲染时,都可以调用该函数,而不必显式调用它,并将查询结果返回给视图。

另外请注意,模型通常是单数的,除非您明确地将它们创建为复数,因此您的品牌模型可以是品牌。如果您的模型恰好是品牌,您只需要将上述代码中的品牌部分更改为品牌。同样,您在模型上使用的是小写的第一个字母——它必须是大写的。

匿名用户

我认为它应该真正起作用。但如果不是,我会这样写。不需要通过view()函数传递变量。

<?php
namespace App\Http\Livewire;
use App\Models\brands;
use Livewire\Component;

class SearchBar extends Component
{

  public $searchTerm;
  public $users

  public function render()
  {
    $searchTerm = '%'.$this->searchTerm.'%';
    $this->users = brands::where('Name', 'like', $searchTerm)->get();
    return view('livewire.search-bar');
  }
}

我希望这是可行的,否则可能是有什么问题的生活线安装?