livewire / livewire

A full-stack framework for Laravel that takes the pain out of building dynamic UIs.
MIT License
22.36k stars 1.56k forks source link

multiple search input #952

Closed rimbaborne closed 4 years ago

rimbaborne commented 4 years ago

Hi. i have an error to adding more filter or multiple search input. I want to ask if there is documentation related to this.

bug Call to undefined method Illuminate\Database\Eloquent\Builder::search()

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithPagination;

class Biodata extends Component
{
    use WithPagination;
    public $search = '';
    public $searchproduk = '';
    public $statusTanda = '2';
    public $perPage = 10;
    public $sortAsc = true;
    public $sortField = 'created_at';

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortAsc = ! $this->sortAsc;
        } else {
            $this->sortAsc = true;
        }
        $this->sortField = $field;
    }

    public function render()
    {
        return view('livewire.biodata', [
            'biodatas' => \App\Models\Biodatum::searchproduk($this->searchproduk)
            ->search($this->search)
            ->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
            ->paginate($this->perPage),
        ]);
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use App\Models\Traits\Attribute\BiodatumAttribute;

class Biodatum extends Model
{
    use BiodatumAttribute,
        SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $fillable = [
        'idagenbaru',
        'nama',
        'email',
        'idprodukreg',
    ];

    public static function search($query)
    {
        return empty($query)
            ? static::query()
            : static::where('nama', 'like', '%'.$query.'%')
                ->orWhere('email', 'like', '%'.$query.'%');
    }

    public static function searchproduk($query)
    {
        return empty($query)
            ? static::query()
            : static::where('idprodukreg', '=', $query);
    }
}

how to add filters or multiple search input ?

Desktop

rimbaborne commented 4 years ago

I already got the answer in the laravel-livewire.com forum and the code works by using this documentation https://laravel.com/docs/7.x/queries#conditional-clauses. thanks.

public function render()
    {
        return view('livewire.biodata', [
            'biodatas' => \App\Models\Biodatum::when($this->searchproduk, function ($query) {
                return $query->where('idprodukreg', '=', $this->searchproduk);
            })
            ->when($this->search, function ($query) {
                return $query->where('nama', 'like', '%'.$this->search.'%');
            })
            ->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
            ->paginate($this->perPage),
        ]);
    }