Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel - Call to a member function map() on array

Tags:

php

laravel

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?

like image 370
gileneusz Avatar asked Jun 29 '18 18:06

gileneusz


1 Answers

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

like image 92
Marcus Avatar answered Oct 31 '22 15:10

Marcus