Yudy Ananda
Yudy Ananda

Reputation: 568

How To Get Search Query From Multiple Columns in Database

I have search form to get information from table named books.

Right now i'm using this controller

public function search(Request $request)
{
    $keyword = $request->input('keyword');
    $query = Book::where('judul', 'LIKE', '%' . $keyword . '%');

    $book_list = $query->paginate(5);
    $pagination = $book_list->appends($request->except('page'));
    $total_book = $book_list->total();
    return view('dashboards.index', compact('book_list', 'keyword', 'pagination', 'total_book'));
}

The problem is the data that i get from the request only available for judul. it just show empty result if the input keyword search addressed to search writter or publisher

I want the search form able to get data from other columns named writters and publisher

Is there any method to get data from multiple column?

Upvotes: 8

Views: 28970

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You can execute conditional queries in many ways.

1. You can use when():

Book::when($keyword, function ($q) use ($keyword) {
        return $q->where('judul', 'LIKE', '%' . $keyword . '%');;
    })
    ->get();

2. Use the where closure:

Book::where(function($q) use ($keyword, $request) {
        if ($request) {
            $q->where('judul', 'LIKE', '%' . $keyword . '%');
        }
    })
    ->get();

3. Do this:

$books = Book::query();

if ($request) {
    $books = $books->where('judul', 'LIKE', '%' . $keyword . '%');
}

$books = $books->get();

Upvotes: 3

Ritesh Khatri
Ritesh Khatri

Reputation: 1301

You can use orwhere to fullfill this, like this

Book::where(function ($query) use($keyword) {
        $query->where('judul', 'like', '%' . $keyword . '%')
           ->orWhere('writters', 'like', '%' . $keyword . '%');
      })
->get();

I hope it helps you.

Upvotes: 22

Related Questions