Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda