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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With