'Laravel Eloquent mapping data with relationship

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?



Solution 1:[1]

Use Laravel's helper method: optional()

The optional function accepts any argument and allows you to access properties or call methods on that object. If the given object is null, properties and methods will return null instead 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 ?
// ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 steven7mwesigwa