0

I have a search function with multiple parameters who seems to not work everytimes on each params for exemple i tested the search query with one param "etat_paiement = 0 ",

normaly i should have no results but i still have one but in the database this record have etat_paiement = 1

where i made a mistake ? thanks a lot in advance

here the code :

 $query = EngagementOrder::query();

            $filters = [
                'structure_engagement_id' => 'structure_id',
                'saison_id' => 'saison_id',
                'etat_paiement' => 'etat_paiement',
                'bl_comptabilite' => 'bl_comptabilite',
            ];


            foreach ($filters as $key => $column) {
                $query->when($request->{$key}, function ($query, $value) use ($column) {
                    $query->where($column, $value);
                });

            }

            $engagements = $query->paginate(10);

in my debug bar i have the query like :

select * from engagement_order limit 10 offset 0

but i run the search with the url like :

https://mydomaine/engagements?etat_paiement=0

UPDATE : here my select box :

{!! Form::select('etat_paiement', array('1' => 'Facture Réglée' , '0' => 'Facture Non Rélgée') , null , ['class' => 'form-control select2 ', 'placeholder' => 'Selectionnez un type de réglement']) !!}
Mathieu Mourareau
  • 1,140
  • 2
  • 23
  • 47

2 Answers2

1

The problem is with the laravel's when method. When you are passing "0" as the first argument to the when function, the below is invoked with the value as "0", which is resolving to be false in this condition: if ($value)

public function when($value, $callback, $default = null)
{
    if ($value) {
        return $callback($this, $value) ?: $this;
    } elseif ($default) {
        return $default($this, $value) ?: $this;
    }

    return $this;
}

Instead of using when, you can generate the query like this:

foreach ($filters as $key => $column) {
        if ($request->has($key)) {
            $query->where($column, $request->{$key});
        }
    }

If you want to use when, change your code to

 foreach ($filters as $key => $column) {
     $query->when($request->has($key), function ($query, $value) use ($column,$key, $request) {
          $query->where($column, $request->$key);
     });
  }
ayip
  • 2,473
  • 1
  • 19
  • 30
0

You may try exists instead of $request->{$key} for example:

$request->exists($key)

In your case $request->{$key} is evaluating to false because etat_paiement=0 has a falsy value. On the other hand, the exists will check if the query parameter/$key is present regardless of the value.

The Alpha
  • 143,660
  • 29
  • 287
  • 307