6

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?

KARASZI István
  • 30,900
  • 8
  • 101
  • 128
user2636197
  • 3,982
  • 9
  • 48
  • 69

4 Answers4

12

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;
});
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • 1
    You might also consider doing this via [an accessor](https://laravel.com/docs/5.3/eloquent-mutators). – ceejayoz Sep 28 '16 at 15:56
  • 9
    The [transform function](https://laravel.com/docs/5.6/collections#method-transform) would be even better, as it doesn't return a new collection instance but modifies the original collection. – w5m Aug 02 '18 at 13:55
1

Solved by adding:

foreach ($allMessages as $message) {
        if ($message->sender_id == $userId) {
            $message->display_name = $message->receivername;
        } else {
            $message->display_name = $message->sendername;
        }
      }
user2636197
  • 3,982
  • 9
  • 48
  • 69
0

You can surely use the laravel's LengthAwarePaginator.

Along with total count of collection you also need to pass the slice of collection's data that needs to be displayed on each page.

$total_count = $allMessages->count();
$per_page = 2;
$current_page = request()->get('page') ?? 1;
$options = [
    'path' => request()->url(),
    'query' => request()->query(),
];

Suppose you want 2 results per page then calculate the offset first

$offset = ($current_page - 1) * $per_page;

Now slice the collection to get per page data

$per_page_data = $collection->slice($offset, $per_page);

$paginated_data = new LengthAwarePaginator($per_page_data, $total_count, $per_page, $current_page, $options);

$paginated_data will have only limited number of items declared by $per_page variable.

If you want next two slice of data then pass api_request?page="2" as your url.

fahad shaikh
  • 593
  • 1
  • 14
  • 29
-1

As I don't know which Laravel version you're using, taking Laravel 5.2 let me give you a smarter way to deal with this (if I get your problem correctly).

You can use Laravel's LengthAwarePaginatior(API Docs).

Don't use paginate method when you are bulding your query, instead of that use simple get method to get simple collection.

$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')
                               ->get();

Now you can populate extra items into that collection based on your certain conditions like this.

if ($allMessages->sender_id == $userId ) {
  // add new value to collection
} else {
  // add new value to collection
}

Now use LengthAwarePaginator, to convert that populated collection into a paginated collection.

$total_count = $allMessages->count();
$limit = 20;
$current_page = request()->get('page');
$options = [
    'path' => request()->url(),
    'query' => request()->query(),
];
$paginated_collection = new LengthAwarePaginator($allMessages, $total_count, $limit, $current_page, $options);

The variable $paginated_collection now can be used to be sent in response. Hope this helps you to deal with your problem.

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
  • Any reason I should not use paginate when I build my query? – user2636197 Sep 29 '16 at 16:12
  • It does not work, "total": 22, "per_page": 20, "from": 1, "to": 22, It should limit the result to 20 but I still get 22 back from the result – user2636197 Sep 29 '16 at 16:28
  • @user2636197 the paginate() method returns a result of type \Illuminate\Contracts\Pagination\LengthAwarePaginator, onto which you cannot use some of the collection methods to process your resulted data. Thats why to make the data processing easier I've taken the result is the form of Laravel collection instead of LengthAwarePaginator. – Saumya Rastogi Oct 03 '16 at 04:23