57122

Laravel Modify collection data

<h3>Question</h3>

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 reciever 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?


<h3>Answer1:</h3>

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; });
<h3>Answer2:</h3>

Solved by adding:

foreach ($allMessages as $message) { if ($message->sender_id == $userId) { $message->display_name = $message->receivername; } else { $message->display_name = $message->sendername; } }
<h3>Answer3:</h3>

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.

来源:https://stackoverflow.com/questions/39751739/laravel-modify-collection-data

Recommend

  • Laravel Modify collection data
  • How to skip angularjs interceptor for an HTTP request?
  • does UILabel have a maximum height?
  • Nuxt SSR with Firebase Integration
  • Google analytics API v4 max results
  • Spring Boot 2 not serializing LocalDateTime
  • how to search similar strings in SQLite [closed]
  • How to resolve “TypeError: NetworkError when attempting to fetch resource.”
  • axis2 Fault: The input stream for an incoming message is null
  • Casting and Generics, Any performance difference?
  • Chart.js Add Commas to Tooltip and Y-Axis
  • Hiding Toolbar smoothly on RecyclerView Scroll?
  • Is it possible to scope ServiceStack.Text.JsConfig settings to just your library?
  • php Mail() and Outlook
  • How to Interfacing SWI Prolog to the Visual Studio 2012
  • react - how do I get the size of a component child elements and reposition them
  • What does the delayed() function do (when used with joblib in Python)
  • Display record even if it doesn't exist
  • Print PDF file and Doc file using C#
  • Styling Ribbon from the RibbonControlsLibrary
  • PHP Codeigniter - ftp_nlist(): Unable to create temporary file. Check permissions in temporary files
  • Switch back to parent tab using selenium webdriver
  • How can I get a spring JdbcTemplate to read_uncommitted?
  • How to send custom logs to Google Play Developer Console?
  • Excel: Cell counts based conditions
  • jquery hide columns in table based on dropdown select
  • Printing a flowdocument with dynamic data in WPF
  • Apache same orgin request blocking
  • Newtonsoft.json serializing and deserializing base/inheirited where classes are from shared projects
  • How to put an object in the air?
  • Query takes almost two seconds but matches only two rows - why isn't the index helping?
  • How to redirect into different page by user type in php and mysql
  • What is the difference between dynamically creating a script tag and statically embed a script tag?
  • Regex not working in java 1.5
  • Using redis as an LRU cache for postgres
  • Bad automatic Triangulation with Mayavi for coloring a surface known only by its corner