I have an eloquent query with a relation but I get ErrorException: Trying to get property 'id' of shop->id.
$collection = Lead::with('shop');
$collection = $collection->orderBy('data', 'DESC');
$collection = $collection->get();
$json = $collection->map(function ($contact) {
return [
'id' => $contact->id,
'name' => $contact->name,
'shop' => [
'id' => $contact->shop->id,
'name' => $contact->shop->name
],
];
});
return response()->json(['contacts' => $json], 200);
Is there any way to use eloquent mapping with relation?
CodePudding user response:
Use Laravel's helper method:
optional()
The
optionalfunction accepts any argument and allows you to access properties or call methods on that object. If the given object isnull, properties and methods will returnnullinstead of causing an error:
Instead of:
// ...
'id' => $contact->shop->id,
'name' => $contact->shop->name
// ...
Use this:
// ...
'id' => optional($contact->shop)->id, ✅
'name' => optional($contact->shop)->name ✅
// ...
