Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda