V
V
VladimirKrasnov2021-02-03 16:18:38
Laravel
VladimirKrasnov, 2021-02-03 16:18:38

How to do Laravel search?

How can I search in Laravel using one form in several fields and in one field?
Now the search method looks like this:

public function search(Request $request)
{
    $result = DB::table('ads')
        ->where('city',  $request->city)
        ->orWhere('category', $request->cat)
        ->get();

    dd($result);    
}


If I'm looking for the 1st field, then everything is fine, but if I'm looking for the 2nd fields, then only the 1st is searched, and the second is ignored.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vladislav Lyskov, 2021-02-03
@Vlatqa

How to make friends in Laravel 5 where()->orWhere and whereIn()?

J
jazzus, 2021-02-03
@jazzus

$cityId = $request->input('city_id');
$categoryId = $request->input('category_id');

$adverts = Advert::when($cityId, function ($query, $cityId) {
    $query->where('city_id', $cityId);
})
    ->when($categoryId, function ($query, $categoryId) {
        $query->where('category_id', $categoryId);
    })
    ->get();

P
Pavel, 2021-02-03
@mechark

Good and relevant article.

T
the5x, 2021-02-04
@the5x

This is where the Builder pattern comes in. You will check if there is a request with a name, then make such and such a selection. If there is a second request, then we perform the action. Fields can be any number

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question