mehdij20
mehdij20

Reputation: 3

Laravel: search and filter data

i want to multi filter data in laravel but i show this error:

Too few arguments to function Illuminate\Support\Collection::get()

Please help me to solve this issue.

public function searchLanding(Request $request)
{

    $landings = Landing::all();

    if(count($landings) && !is_null($request->title)) {
        $landings = $landings->where("name", "LIKE", "%{$request->title}%")->get();
    }

    if (count($landings) && !is_null($request->start_at)) {
        $landings = $landings->where('start_at', '>=', $request->start_at)->get();
    }

    if (count($landings) && !is_null($request->end_at)) {
        $landings = $landings->where('end_at', '<=', $request->end_at)->get();
    }

}

Upvotes: 0

Views: 3879

Answers (1)

Anurat Chapanond
Anurat Chapanond

Reputation: 2987

public function searchLanding(Request $request)
{

    $landings = Landing::query();

    if(!is_null($request->title)) {
        $landings->orWhere("name", "LIKE", "%{$request->title}%");
    }

    if (!is_null($request->start_at)) {
        $landings->orWhere('start_at', '>=', $request->start_at);
    }

    if (!is_null($request->end_at)) {
        $landings->orWhere('end_at', '<=', $request->end_at);
    }

     return $landings->get();
}

Note:
You shouldn't call all() or get() when you are still building your query, only call them when you want to get the result.

Use where() when you want all conditions to be true,
or use orWhere() when you want one of the conditions to be true.

In the example above, only one of the conditions needs to be true e.g. search found in title or after start_at or before end_at.

Upvotes: 2

Related Questions