How to filter on a search box a boolean in Laravel 8

Viewed 924

I want my boolean field which is displayed as 'Approved' and 'Not Approved' in the frontend, is it possible for me to filter this as displayed in the frontend?

My filtering logic

$search = '%'.$this->search . '%';
        $comments = Comment
        ::where('title', 'like', $search)
       ->orWhere('name', 'like', $search)
       ->orWhere('email', 'like', $search)
       ->orWhere('message', 'like', $search)
       ->orWhere('approved', 'like', $search)
       ->orderBy('created_at', 'desc')       
       ->paginate($this->paginate);

I can only search the approved column as 0 and 1.

1 Answers

Try the below query -

$search = '%'.$this->search . '%';
$searchInput = $this->search;

$comments = Comment::where('title', 'like', $search)->where(function ($q) use ($searchInput, $search) {
    $q->orWhere('name', 'like', $search);
    $q->orWhere('email', 'like', $search);
    $q->orWhere('message', 'like', $search);
    $q->orWhereRaw("(CASE WHEN approved = 1 THEN 'Approved' ELSE 'Not Approved' END) LIKE '%$searchInput%'");
})->orderBy('created_at', 'desc')->paginate($this->paginate);
Related