Search form in Laravel

0

I'm doing a news section, which to find a news I have the following form:

The question I have is, how can I do a search engine, depending on the number of fields that are completed. For example, someone can search for news only by keyword, or date. Or other people can complete Sector, company, source, or all fields, that is, you can do a search with any field and any combination of these

    
asked by Juan Pablo B 16.04.2018 в 14:06
source

1 answer

1

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'));
}
    
answered by 17.04.2018 / 00:39
source