Problems with where nested in Query Builder Laravel 5

-1

I have the problem when I pass empty parameters in a filter. I am using a scope where I filter by several parameters, including year, month, province, and name.

About Name there are no problems since I use a like. But in others when filter, the parameters are optional. I can filter by all or by some. But here the question when I filter by some and leave another vacuum. this where looking for a vacuum and can not find it, makes the query empty.

The first solution I can think of is a cumbersome if nested with the 9 options (since they are 3 empty possibilities) and putting in each 1 the where are not empty ... I want to believe that there is a better solution

public function scopeSearch($query, $request)
{

    if($request->nombre == "" && $request->provincia_id == "" && $request->meses =="" && $request->anio == "")
            return $query
                    ->where('fecha', '>=', Carbon::now());


    return $query
                ->where('nombre','LIKE',"%$request->nombre%")
                ->whereMonth('fecha', $request->meses)
                ->whereYear('fecha', $request->anio);
                //->where('provincia_id','=',"$request->provincia_id");
}
    
asked by Cidius 13.10.2016 в 03:04
source

1 answer

0

It's almost a habit to answer my own questions. But I think the solution can contribute

Searching and joining pieces I found that you can do a where as a function and within the doing if using the abstract class of Input. So:

public function scopeSearch($query, $request)
{

    if($request->nombre == "" && $request->provincia_id == "" && $request->meses =="" && $request->anio == "")
            return $query
                    ->where('fecha', '>=', Carbon::now());

    $eventos= Evento::where(function($query) use($request) {

     if(Input::has('provincia_id'))
        $query->where('provincia_id','=',"$request->provincia_id");

     if(Input::has('meses'))
        $query->whereMonth('fecha', $request->meses);

    if(Input::has('anio'))
        $query->whereYear('fecha', $request->anio);

    if(Input::has('nombre'))
        $query->where('nombre','LIKE',"%$request->nombre%");

     });

    return $eventos;
}

must use the Fascades

use Illuminate\Support\Facades\Input;

Basically it verifies each input with its id and if it has any data (in my case they were select but it works the same), if there is a query it does not pass it.

It would not be necessary to use the scope, you can use it in the controller. I have to investigate if it is the neater way. But it seems that if

    
answered by 13.10.2016 / 05:44
source