Laravel - replace null with empty array when no relation is found

Posted 2 years ago by ilarioengler

Is it possible to replace null with an empty array when no relation is found?

E.g. The customer has contacts and contracts but one of the contract has no web.

$customers = Customer::with('contacts', 'contracts.web')
        ->orderBy('company')->orderBy('prename')->get();

The result would be as following...

2 => array:21 [
  "id" => 1
  "contacts" => array:2 [
    0 => array:12 [
      "id" => 1
      "customer_id" => 1
    ]
    1 => array:12 [
      "id" => 2
      "customer_id" => 1
    ]
  ]
  "contracts" => array:2 [
    0 => array:9 [
      "id" => 1
      "customer_id" => 1
      "web" => array:7 [
        "id" => 1
        "contract_id" => 1
      ]
    ]
    1 => array:9 [
      "id" => 2
      "customer_id" => 1
      "web" => null // should be replaced with []
    ]
  ]
]

As I read in the docs (Constraining Eager Loads), it's only possible to manipulate the query with constraining eager loads.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.