(laravel) How to ignore null values in $ request-all ()?

0

I'm developing a filter system in which the user can or may not fill some fields of a form. In the controller, I'm trying to do a where in the following way:

    //demais filtros
    $imoveis = Imovel::where([
        'finalidade' => $request['finalidade'],
        'tipo_id' => $request['tipo_id'],
        'cidade_id' => $request['cidade_id'],
        'bairro' => $request['bairro'],
        'area' => $request['area'],
        'quartos' => $request['quartos'],
        'banheiros' => $request['banheiros'],
        'suites' => $request['suites'],
        'garagens' => $request['garagens'],
    ])->get();

However, I want to ignore somehow the values that were not filled by the user, and which come as null in the request.

An example of dd ($ request-> all ()) is:

  

array: 14 [▼     "_token" = > & Quot;     "id" = > null     "name" = > null     "purpose" = > "1"     "type_id" = > null     "ciudad_id" = > null     "neighborhood" = > null     "area" = > null     "rooms" = > null     "suites" = > null     "bathrooms" = > null     "garages" = > null     "minimum value" = > null     "max value" = > null   ]

    
asked by anonymous 03.01.2018 / 17:17

3 answers

3

You can use the array_where helper.

Example:

$a = ['a' => 'b', 'c' => null];

$filtered = array_where($a, function($value, $key){ 
 return !is_null($value); 
}); // ['a' => 'b']

In this way you will filter the array with all values, returning only non-null values.

    
03.01.2018 / 17:33
0

You can use in_array maybe, I do not know laravel, but I think it should work.

$minhaArray = array("Nome" => "Lucas", "id" => "1", "Idade" => null);

if(in_array(null, $minhaArray)){
  echo"teste1"; 
} else {
   echo "teste2";
}
    
03.01.2018 / 17:21
0

Unfortunately, Laravel's $ request does not have any method that can help you, but you can solve this well with PHP's array_filter function. The array_filter function filters elements of an array using a callback function.

To resolve your issue use the following code:

// No seu caso esse $array receberá o seu $request->all();
// $array = $request->all();


$array = ['name'=>'fulano','email'=>'[email protected]','age'=>null];

// Vamos atribuir o retorno da função array_filter a uma nova variável
$fields = ( array_filter( $array , function( $value, $key ) {
    return $value != null; // retorna todos os valores que forem diferentes de null
}, ARRAY_FILTER_USE_BOTH ) );

echo  '<pre>';
print_r($fields);
die;

// Resultado da variável $fields
Array
(
    [name] => fulano
    [email] => [email protected]
)

The array_filter function receives 3 parameters, the first is the array you want to filter, the second is your callback function, and the third is the flag (ARRAY_FILTER_USE_KEY, ARRAY_FILTER_USE_BOTH).

You can take a look at the PHP documentation and understand it better. ( Documentation )

    
03.01.2018 / 18:45