skip to Main Content

I am trying to find if search query contains result , if not then return null
here is the code , but even the search is not present in DB it is showing previous search results

if (!empty($searchInput)) {
    $complexityLevel->join('organizations', 'complexity_levels.organization_id', '=', 'organizations.id');
    $complexityLevel->where("complexity_levels.name", "like", "%$searchInput%")
        ->orWhere("complexity_levels.experience_range_start", "like", "%$searchInput%")
        ->orWhere("complexity_levels.experience_range_end", "like", "%$searchInput%")
        ->orWhere("organizations.name", "like", "%$searchInput%")
    $complexityLevel->select('complexity_levels.*', 'organizations.name');                   
} 

if (!empty($complexityLevel))  {
    return  $complexityLevel->orderBy($sortBy, $sortOrder)->paginate($pageSize);
}
return null;

2

Answers


  1. In your case you are checking if $complexityLevel is not empty. But it will not be empty since it’s a query, not a collection as you expect. To do what was intended you’d need something like this:

    if (!empty($searchInput)) {
        $complexityLevel->join('organizations', 'complexity_levels.organization_id', '=', 'organizations.id')
            ->select('complexity_levels.*', 'organizations.name')
            ->where("complexity_levels.name", "like", "%$searchInput%")
            ->orWhere("complexity_levels.experience_range_start", "like", "%$searchInput%")
            ->orWhere("complexity_levels.experience_range_end", "like", "%$searchInput%")
            ->orWhere("organizations.name", "like", "%$searchInput%")
            ->orderBy($sortBy, $sortOrder)
            ->paginate($pageSize);                   
    } 
    return count($complexityLevel) ? $complexityLevel : null;
    
    Login or Signup to reply.
  2. If you want to check if $complexityLevel is not empty, you can use -> isNotEmpty()

    In your query case

    if (empty($searchInput)) {
      return null;
    }
    
    $complexityLevel->query()
       ->join( ... )
       ->where( ... )
       ....
       ->orderBy($sortBy, $sortOrder)
       ->paginate($pageSize);
    
    if ($complexityLevel->isNotEmpty()) {
      return $complexityLevel;
    }
    
    return null;
    

    or you can also check when empty

    if ($complexityLevel->isEmpty()) {
      return null;
    }
    

    Here is some reference:
    https://laravel.com/api/8.x/Illuminate/Contracts/Pagination/Paginator.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search