Ad

Why Isn't My Third Condition Working In Search?

I am trying to get a searched result and I have the following code:

public function search(Request $request){ 
    $from = $request->from;
    $to = $request->to;
    $word = $request->word;  
    if(empty($word) || $word == null){
        $searched = Post::whereBetween('created_at', [$from, $to])->paginate(10);
    } elseif(!empty($word) && !empty($from) && !empty($to)){ 
        $searched = Post::where('title', 'LIKE', '%' . $word . '%')
        ->orWhere('content', 'LIKE', '%' . $word . '%')
        ->orWhere('subtitle', 'LIKE', '%' . $word . '%')
        ->whereBetween('created_at', [$from, $to])
        ->paginate(10); 
    } elseif(empty($from) && empty($to) && !empty($word)){
        $searched = Post::where('title', 'LIKE', '%' . $word . '%')
        ->orWhere('content', 'LIKE', '%' . $word . '%')
        ->orWhere('subtitle', 'LIKE', '%' . $word . '%')
        ->paginate(10);
    }

    return view('page.search', compact('searched', 'from', 'to'));
}

The first and second condition are working but not the last. What am I missing or doing wrong here?

Ad

Answer

try this one

  • for example if word found then search with like then first condition true
  • if user set from and to date then second condition true
  • if user fill both(word and date) then your both condition true..

  • if your does not fill any value then get first 10(ten) posts only(none of condition match)

    public function search(Request $request){
    
        $posts = Post::query();
        $from = $request->from;
        $to = $request->to;
        $word = trim($request->word);
    
        if($word && !empty($word)){
               $posts->where('title', 'LIKE', '%' . $word . '%')
                ->orWhere('content', 'LIKE', '%' . $word . '%')
                ->orWhere('subtitle', 'LIKE', '%' . $word . '%');
        }
    
        if(!empty($from) && !empty($to)){
            $posts->whereBetween('created_at', [$from, $to]);
        }
    
        $searched = $posts->paginate(10);
    
        return view('page.search', compact('searched', 'from', 'to'));
    }
    
Ad
source: stackoverflow.com
Ad