Mehdi Alikhani
Mehdi Alikhani

Reputation: 141

Laravel search system based on input values

I have a search form with 4 inputs such as username, text, fromDate, toDate, and users can search with just one field , the problem is i don't know how to build a query with inputs which have values, I can compare them if each one of them has value or not like this :

        if ($request->input('fromdatepicker') && $request->input('todatepicker') && $request->input('search-text')){

            $query = \App\InstaPost::WhereFullTextWithTimestamp($request->input('search-text'), $from_timestamp, $to_timestamp)->paginate(12);
           
        }else if ($request->input('search-text') && empty($request->input('fromdatepicker')) && empty($request->input('todatepicker'))){
            $query = \App\InstaPost::WhereFullText($request->input('search-text'))->paginate(12);
        } else if(empty($request->input('search-text')) && $request->input('fromdatepicker') && $request->input('todatepicker')){
            $query = InstaPost::WhereTimestamp($from_timestamp, $to_timestamp)->paginate(12);
        }

i have different scenarios:

scenario 1 enter image description here enter image description here

as you can see so many scenarios, but as you know it'll be a huge mess ! these if's is just for 3 inputs! and i should compare them for each scenarios , hope you understand the problem and help me. I'm using Laravel-Mongodb(jessengers) and i should find out which input has value and then make a query and add them to this code block :

    public function scopeWhereFullTextWithTimestamp($query,$search,$from_timestamp , $to_timestamp)
    {
        $query->getQuery()->projections = ['score'=>['$meta'=>'textScore']];

        $query->orderBy('post.taken_at_timestamp','DESC');

        return $query->whereRaw([
            '$text' => ['$search' => $search],
            'post.taken_at_timestamp'=> [
                '$gte' => $from_timestamp,
                '$lte' => $to_timestamp
            ]

        ]);

this is for search-text , fromDate and toDate inputs,

Upvotes: 0

Views: 385

Answers (1)

Aless55
Aless55

Reputation: 2709

You can concatenate queries based on the input, something in this direction should do the trick.

$base_query = App\InstaPost;

if(!is_null($request->input('search-text'))){
$base_query->WhereFullText($request->input('search-text'));
}
if...
if..

$result = $base_query->get(); //or paginate()

Upvotes: 1

Related Questions