Home > front end >  Laravel Eloquent mapping data with relationship
Laravel Eloquent mapping data with relationship

Time:03-12

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 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 ✅
// ...
  • Related