Does anyone know how I can do this type of Eloquent query?

0

I need to have a query builder. The only way that has occurred to me is to make a string, and in the string form the eloquent query. I only have a problem executing the query.

$variable = "where('a','asd')->get()";
return Modelo::$variable;

This error comes out:

Access to undeclared static property: App \ Models \ Api \ Ela \ Model :: $ variable "

    
asked by Alberto Ortega 21.11.2018 в 21:23
source

1 answer

1

You can build the Eloquent query based on what you get in the following way:

According to what I understood, different parameters come up for you to build the query, assuming that one of those filters that arrive to you is called filter_name, and after encoding and processing the json or how you want to manage it, what came in that parameter is saved in a variable $filtro_nombre or the same is null ;

$query = Miobjeto::select("un_campo")
->when($filtro_nombre != null, function ($query) use ($filtro_nombre) {
    return $query->where('nombre', $filtro_nombre);
})
//aca puedes seguir agregando todos los when necesarios.
->get();

return $query;

Now if you want you can also use Query Builder:

$query= DB::table('mis_objetos')->select("un_campo");

if($filtro_nombre != null)
    $query->where('nombre',$filtro_nombre);

//aca puedes seguir construyendo la consulta.

return $query->get();

I hope it helps you.

Greetings!

    
answered by 22.11.2018 / 20:51
source