Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 ✅
// ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading