6

I'm trying to make an array on my contact list, basing on my message table fromContact relation:

    $messages = Message::where('offer_id', $id)->get();
    $contacts = array();
    foreach($messages as $message){
      $contacts[] = $message->fromContact;
    }

next I'm trying to make a map on contact, using $unreadIds that are result of other query on messages table:

    $contacts = $contacts->map(function($contact) use ($unreadIds) {
        $contactUnread = $unreadIds->where('sender_id', $contact->id)->first();
        $contact->unread = $contactUnread ? $contactUnread->messages_count : 0;
        return $contact;
    });

and this is not working... I've got simply message with error: Call to a member function map() on array

and I understand it, I should not use map() on array - so I tried many ways to convert it to object - all failed.

for example converting contacts into object after array loop

 $contacts = (object)$contacts;

gives error: "message": "Call to undefined method stdClass::map()",

Maybe anyone knows how to fix that?

1 Answer 1

12

Use laravel helper collect on the array then use map.

$collection = collect($contacts);

$collection->map(function($contact) use ($unreadIds) {
    $contactUnread = $unreadIds->where('sender_id', $contact->id)->first();
    $contact->unread = $contactUnread ? $contactUnread->messages_count : 0;
    return $contact;
});

https://laravel.com/docs/5.6/collections

Sign up to request clarification or add additional context in comments.

2 Comments

I declared empty $contacts = collect([]); before foreach loop, but this also works!
I'm glad it helped!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.