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

Asked

Viewed 701 times

0

I am developing a filter system in which the user may or may not fill in some form fields. In the controller, I’m trying to do a Where as follows:

    //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 somehow ignore the values that were not filled in by the user, and that come as null in the request.

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

array:14 [ "_token" => "Nbfiyyw7xqfqr2j858zq7stliaqoyb0mzo1ckknz" "id" => null "name" => null "purpose" => "1" "id type" => null "city_id" => null "neighborhood" => null "area" => null "rooms" => null "suites" => null "toilets" => null "garages" => null "valueMinimo" => null "valueMaximo" => null ]

3 answers

3


You can use the helper array_where.

Example:

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

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

This way will filter the array with all values, returning only values that are not null.

  • Thank you for the reply! You attended well to what I needed!

0

You can use in_array maybe, I don’t know Windows, but I think it should work.

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

if(in_array(null, $minhaArray)){
  echo"teste1"; 
} else {
   echo "teste2";
}

0

Man unfortunately the $request of Laravel has no method that can help you, but it can be solved well with the function php array_filter. The function array_filter filters elements of an array using a callback.

To solve your problem 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 takes 3 parameters, the first will be the array you want to filter, the second will be its callback function and the third will be the flag(ARRAY_FILTER_USE_KEY, ARRAY_FILTER_USE_BOTH ).

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.