AMAFsoft
AMAFsoft

Reputation: 53

laravel 5.7 : how to filter search?

I'm trying to make an advanced search by multiple inputs :

$orders = new Order;

        if ($request->has('client_id')) {
            $orders->where('client_id' ,$request->client_id);
        }

        if ($request->has('city_id')) {
            $orders->where('city_id', $request->city_id);
        }

        dd($orders->get());

but this code returns all database records. And if i use get method with the query in one line it works just fine!

$orders->where('city_id', $request->city_id)->get();
dd($orders);

Any ideas?

Upvotes: 1

Views: 2296

Answers (3)

omitobi
omitobi

Reputation: 7334

You should set the variable $order each time you add the clause e.g:

$orders = new Order;

if ($request->has('client_id')) {
     $orders = $orders->where('client_id' ,$request->client_id);
}

if ($request->has('city_id')) {
    $orders = $orders->where('city_id', $request->city_id);
}
 // then run $orders->get(); or other stuff

The new values of $orders would have been updated accordingly.

Its quite interesting that way you declared the model caused the problem. By creating a new instance of Order using new keyword, the model has not recognize the default query builder (for some reason), meaning that dump()ing the model there's no wheres array to push the new where into.

Other ways you could do it is to have an initial query e.g

Order::whereNotNull('id');

//Otherwise as suggested use `->query()` or `newQuery()`

Mind you query() is like an alias of newQuery() except that query() creates a fresh instance of the model before calling newQuery().

You can instead use getQuery() to retrieve the $query property of the model instead of the two as you don't need to re-instantiate the builder. Therefore, you can have:

 $orders = Order::getQuery();

if ($request->has('client_id')) {
     $orders->where('client_id' ,$request->client_id);
}

if ($request->has('city_id')) {
    $orders->where('city_id', $request->city_id);
}
 // then run $orders->get(); or other stuff

PS: I tested this on L5.4

Upvotes: 2

Syed Arif Iqbal
Syed Arif Iqbal

Reputation: 1427

try to initialize the query

$query = Order::select("*");

if ($request->has('client_id')) {
   $query->where('client_id' ,$request->client_id);
}

if ($request->has('city_id')) {
   $query->where('city_id', $request->city_id);
}

dd($query->get());

Upvotes: 1

kenken9999
kenken9999

Reputation: 795

a simple way, just do this

$query = Order::query();

if ($request->has('client_id')) {
    $query->where('client_id' ,$request->client_id);
}

if ($request->has('city_id')) {
    $query->where('city_id', $request->city_id);
}

dd($query->get());

Upvotes: 3

Related Questions