Home > Software engineering >  Laravel : convert any value of array which have null
Laravel : convert any value of array which have null

Time:06-29

I have array gets from database :

public function get_orders($phone)
{
    $customer = User::where('phone',$phone)->get();
    $c_id = $customer[0]->id;
    $orders = Order::where('cusID',$c_id)->orderBy('id','DESC')->get();
}

I get this list :

[
    {
        "id": 5375,
        "cusID": 1015,
        "websiteID": null,
        "brandID": 8052
    },
    {
        "id": 5378,
        "cusID": 1015,
        "websiteID": 1,
        "brandID": null
     }

Now how can I convert all null values to empty string once?

I tried this but dont work

foreach ($orders as $order) {
    foreach ($order as $key => $value) {
        if (is_null($value)) {
             $order[$key] = "";
        }
    }
  return $orders;
 }

also I tried this but not works:

array_map(function($v){
                return ($v === null) ? "" : $v;
              }, $order->toArray());

CodePudding user response:

I Solved it by change order to Array:

foreach ($orders as $order) {

            foreach ($order->toArray() as $key => $value) {
                
                if (is_null($order[$key])) {
                     $order[$key] = "";
                }
            }
}
  • Related