Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel modify Collection data

I wonder if Laravel have any helper to modify a collection.

What I need to do is to make a query with paginate() then check if the logged in users ID match the sender or receiver and based on that add a new value to the output:

$userId = Auth::guard('api')->user()->user_id;
$allMessages = Conversation::join('users as sender', 'conversations.sender_id', '=', 'sender.user_id')
                               ->join('users as reciver', 'conversations.recipient_id', '=', 'reciver.user_id')
                               ->where('sender_id',$userId)->orWhere('recipient_id',$userId)
                               ->orderBy('last_updated', 'desc')
                               ->select('subject','sender_id','recipient_id', 'sender_unread', 'recipient_unread', 'last_updated', 'reciver.username as receivername', 'sender.username as sendername')
                               ->paginate(20);

Now I want to do something like:

if ($allMessages->sender_id == $userId) {
    // add new value to output
    newField = $allMessages->sendername
} else {
    // add new value to output
    newField = $allMessages->receivername
}

Then send the data with the new value added

return response()->json(['messages' => $allMessages], 200);

Is this possible?

like image 739
user2636197 Avatar asked Sep 28 '16 15:09

user2636197


2 Answers

You're better off using the Collection class's built-in functions for this. For example, the map function would be perfect.

https://laravel.com/docs/5.3/collections#method-map

$allMessages = $allMessages->map(function ($message, $key) use($userId) {
    if ($message->sender_id == $userId) {
        $message->display_name = $message->receivername;
    } else {
        $message->display_name = $message->sendername;
    }

    return $message;
});
like image 68
ceejayoz Avatar answered Sep 23 '22 19:09

ceejayoz


Solved by adding:

foreach ($allMessages as $message) {
        if ($message->sender_id == $userId) {
            $message->display_name = $message->receivername;
        } else {
            $message->display_name = $message->sendername;
        }
      }
like image 32
user2636197 Avatar answered Sep 23 '22 19:09

user2636197