1

I have an array for showing users' contacts list to each other.

I want to add ->paginate(10) features for json response but I could not find where I must put it.

My index function:

public function index()
{
    $contacts = [];
    $user = request()->user();
    // Loop through the contacts and format each one

    Contact::for($user->id)->get()->each(function ($contact) use ($user, &$contacts) {
        $friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1;
        $contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()];
    });

    return response()->json($contacts);
}
3
  • Can you specify what you are doing in the index()? Commented Dec 5, 2018 at 10:06
  • @sadaiMudiNaadhar I am using pusher service for instant chat app, so I want to show created chat contacts to users like whatsapp. Im showing created chat lists to users at this index() function, its working well but I want to add pagination to it for infinite scroll. Commented Dec 5, 2018 at 10:23
  • Looks like you are doing thing in a complex way. Any way i will post a clue Commented Dec 5, 2018 at 10:26

4 Answers 4

2

You can create a collection for the contact and use LenfthAwarePaginator

 class ContactResourceCollection extends ResourceCollection
{
/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request
 * @return array
 */
public function toArray($request)
{
    $response = [
        'data' => $this->collection,
    ];

    if($this->resource instanceof LengthAwarePaginator)
    {
        $response['pagination'] = [
            'total' => $this->resource->total(),
            'lastPage' => $this->resource->lastPage(),
            'perPage' => $this->resource->perPage(),
            'currentPage' => $this->resource->currentPage(),
            'nextPageUrl' => $this->resource->nextPageUrl(),
            'previousPageUrl' => $this->resource->previousPageUrl(),
        ];
    }
    return $response;
  }
}

In the controller method add this line:

 return new UserResourceCollection($users);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reply but I think there will be easiest way to do it, if I can not find easiest way I am gonna review this method, thanks :)
I tried so many things but lastly this method worked, thanks :)
1

Here is the total code

$contacts = Contact::where('user_id', $user->id)->paginate(12);
if($contacts->count()){                    
    $pageIndex = array();
    $lastPage = $contacts->lastPage();
    $user = request()->user();

    for($i= 2; $i<=$lastPage; $i++){
        array_push($pageIndex, $i);
    }

    return response()->json([
        'contacts' => $contacts->map(function ($contact) use ($user) {
                          if($contact->user1_id  === $user->id){

                            return [
                                'friend' => $contact->user2,
                                'room' => $contact->room,

                            ];

                        } else {

                            return [

                                    'friend' => $contact->user1,
                                    'room' => $contact->room,
                            ]; 

                        }
                    })->toArray(),  
        'per_page' => $contacts->perPage(),
        'on_first_page' => $contacts->onFirstPage(),
        'last_page' => $contacts->lastPage(),
        'first_page_url' => $contacts->url(1),
        'next_page_url' => $contacts->nextPageUrl(),
        'prev_page_url' => $contacts->previousPageUrl(),
        'last_page_url' => $contacts->url($contacts->lastPage()),
        'total' => $contacts->total(),
        'pageIndexArray' => $pageIndex,
        'errors' => false,
    ]);
} else {

  // Do Nothing
}

Call GET 'URL?page='+Page_index to get the response in JS (AJAX)

9 Comments

I tried to edit my code with looking at your code but I could not combined it correct, Im not so good at Laravel, Can you combine it for me ? Thanks :)
sure, can you explain what you are doing here $friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1; $contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()]
if you review this tutorial you can understand what Im trying to doing (Scroll down little bit and look at "THE CONTACTS ENDPOINT" please) pusher.com/tutorials/… He explained it like this; In the index method, we get all the contacts of the user and loop through each contact and append the contact to the contacts array. Finally we return the contacts as the response.
If you can , please give me the print_r($contacts[]); so that i can know what you meant
I did made this controller function for mobile app so I dont have any view for print it on web, is json result enough for understand ? Json Result : 0bin.net/paste/…
|
0

I am not sure but try : replace get() to paginate(10)

Contact::for($user->id)->paginate(10)->each(function ($contact) use ($user, &$contacts) {
        $friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1;
        $contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()];
    });

1 Comment

I did tried this one but it was not work, thanks for reply :)
0

Can you change the query into:

$contacts = Contact::for($user->id)->paginate(10);

Then after this query you can use for loop for $contact;

 foreach ($contacts as $key => $contact)
 {
   $friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1;
   $contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()];
 }

Paginate first before get into loop/each.

12 Comments

Thanks for reply, I did made this changes but it changed json results ?
since we have a variable of $contacts you can change your $contacts = []; into $contact_array = []; and change other variable name handling the array., then return code return response()->json($contact_array);
I did made this changes too but its showing empty json results :/ Full code; public function index() { $contact_array = []; $user = request()->user(); $contacts = Contact::for($user->id)->paginate(10); foreach ($contacts as $key => $contact) { $friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1; $contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()]; } return response()->json($contact_array); }
try these public function index() { $contact_array = []; $user = request()->user(); $contacts = Contact::for($user->id)->paginate(10); foreach ($contacts as $key => $contact) { $friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1; $contact_array[] = $friend->toArray() + ['room' => $contact->room->toArray()]; } return response()->json($contact_array); }
Thanks it works again but like before these changes. it does not added pagination :/
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.