Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
Laravel and php best multiple search method

I have a controller that get the four inputs from a search form.

SearchController.php code

public function results(Request $request) {
    $text           = $request -> text;
    $pet            = $request -> pet;
    $category       = $request -> category;
    $city           = $request -> city;
    $searchArray    = [];
    if(empty($text) && empty($pet) && empty($category) && empty($city)) {
        Session::flash('danger', "You didn't select any search any search.");
        return redirect() -> back();
    }

    //SEARCH CODE HERE
}

What I am trying to do

I am trying to search 4 columns in my database

Problem is

I need also to search the 4 columns in one query.

That means that I need to check if the $text variable is not empty and $pet variable is not empty then I have to do this query:

if(!empty($text) && !empty($pet))
            $result = Post::where('text', 'like', '%'.$text.'%') -> where('text', $pet) -> get();

This method will work fine but I will have multiple if statements that will check all the possibilities.

Is there faster and optimal solution?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Option 1

Build logic manually. This is the best way in many situations. An example:

$result = Post::query();

if (!empty($text)) {
    $result = $result->where('text', 'like', '%'.$text.'%');
}

if (!empty($pet)) {
    $result = $result->where('pet', $pet);
}

if (!empty($category)) {
    $result = $result->where('category', $category);
}

if (!empty($city)) {
    $result = $result->where('city', 'like', '%'.$city.'%');
}

$result = $result->get();

Option 2

Use conditional clauses. Example:

Post::when($text, function ($q) use ($text) {
        return $q->where('text', 'like', '%'.$text.'%');
    })
    ->when($pet, function ($q) use ($pet) {
        return $q->where('pet', $pet);
    })
    ->when($category, function ($q) use ($category) {
        return $q->where('category', $category);
    })
    ->when($city, function ($q) use ($city) {
        return $q->where('city', 'like', '%'.$city.'%');
    })
    ->get();
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!