You can do it this way, based on the fields that you receive in the request vas arming the query, for example:
The new query for the News model starts
$noticia = Noticia::newQuery();
An example of search based on a field of news:
if($request->has('palabra_clave')){
$noticia->where('nombre', 'like', $request->palabra_clave);
}
Some search examples based on model Noticia
relationships with other models, in this case assuming that there is a model Sector
and a model Fuente
and that their relationships are declared as sector
and fuente
respectively:
if($request->has('sector')){
$noticia->whereHas('sector', function ($query) {
$query->where('nombre', 'like', $request->sector);
});
}
if($request->has('fuente')){
$noticia->whereHas('fuente', function ($query) {
$query->where('nombre', 'like', $request->fuente);
});
}
Finally we execute the query that was assembled and we return the result to the view:
$noticias = $noticias->get();
return view('tuvista', compact('noticias'));
Here is the code as it could be seen in a search method:
public function busqueda(Request $request){
$noticia = Noticia::newQuery();
if($request->has('palabra_clave')){
$noticia->where('nombre', 'like', $request->palabra_clave);
}
if($request->has('sector')){
$noticia->whereHas('sector', function ($query) {
$query->where('nombre', 'like', $request->sector);
});
}
if($request->has('fuente')){
$noticia->whereHas('fuente', function ($query) {
$query->where('nombre', 'like', $request->fuente);
});
}
$noticias = $noticias->get();
return view('tuvista', compact('noticias'));
}