I have been in different ways to solve a problem but I still have not been able to, I am consuming an api in laravel where I want to make a filter with several optional parameters
The problem is that in my function when I receive the parameters and I want to do my query using eloquen it tells me that the parameters are undefined
Here is the endpoint that I consult and how it sends the parameters
avisos/titulo/ejemplo/ubicacion/320/estado/2/categoria/3
In my api routes file
Route::get('avisos/titulo/{titulo?}/ubicacion/{ubicacion?}/estado/{estado?}/categoria/{categoria?}', [AvisosController::class, 'prueba']);
here my controller and function that is executed
public function prueba($titulo="",$ubicacion=0,$estado=0,$categoria=0){
//$ubicacionRecibida = $ubicacion;
//Cuando retorno de esta formas las variables tienen contenido
// return response()->json([
// 'titulo' => $titulo,
// 'categoria' => $categoria,
// 'ubicacion' => $ubicacion,
// 'estado' => $estado
// ], Response::HTTP_OK);
//Pero al intentar usarla en mi consulta la variable es undefined
$avisos = new Avisos();
$avisos = Avisos::select(
'Avisos.id',
'Avisos.titulo',
'Avisos.descripcion',
'Avisos.imagen',
'Avisos.created_at as fecha',
'Avisos.vistas',
'users.name',
'users.id as idUsuario',
'comunas.nombreComuna',
'ciudads.nombreCiudad'
)->join('categorias','categorias.id', '=','avisos.idCategoria')
->join('users','users.id', '=','avisos.idUsuario')
->join('comunas','comunas.id','=','avisos.idComuna')
->join('ciudads', 'ciudads.id','=','comunas.idCiudad')
->with('valoraciones')
->when($ubicacion, function ($query) {
$query->where('avisos.idComuna','=',$ubicacion);#aca es undefined linea 250
})
->get();
// ->when($categoria, function ($query) {
// $query->where('avisos.idCategoria','=',2);
// })->when($estado, function ($query) {
// $query->where('avisos.idEstado','=',1);
// })
return $avisos;
}
the error i get
ErrorException: Undefined variable $ubicacion in file C:\.....\app\Http\Controllers\V1\AvisosController.php on line 250
The parameters arrive well at the controller, in fact if I do a return $parametro;
it returns it correctly the problem is when I try to use it in my query, it tells me that it is undefined , and it happens to me with all the other parameters (status, category, location, title.
Hopefully someone has gone through this before and let me know if I'm missing something to do or how else I can try
After trying different solutions, it was really something extremely simple:
After analyzing more in detail, I realized that I must pass the parameter to the function, and it would be as follows:
I hope it serves for posterity.