strategicsdemexico's avatar

Pagination and Vue.js

I'm doing ajax request to get all Events from my Event Model

public function index(Request $request)
{
    $events = $this->eventRepo->paginate(15);
    if( $request->ajax() ) return $events;
    return view('events.index', compact('events'));
}

This events collection has a collection of the event model (obviously but i have to mentioned), i have the relation this event with the users model.

public function user()
{
    return $this->belongsTo('App\User');
}

On my Vue instance I do the post to the right route i get everything almost in place but how do i get the relation with the user on the client side with javascript?

This is what I do on the Vue instance on the method to fetch all events.

methods:{
    fetchEvents: function(){
        this.$http.post('api/events', function(events){
            console.log(events)
        });
        }
}

This is what i get on the response of the request.

{
  "total": 2,
  "per_page": 15,
  "current_page": 1,
  "last_page": 1,
  "next_page_url": null,
  "prev_page_url": null,
  "from": 1,
  "to": 2,
  "data": [
    {
      "id": "3",
      "event": "asdasd ",
      "user_id": "2",
      "created_at": "2015-06-20 01:30:40",
      "updated_at": "2015-06-20 01:30:40"
    },
    {
      "id": "2",
      "event": "asdasd",
      "user_id": "2",
      "created_at": "2015-06-20 01:28:02",
      "updated_at": "2015-06-20 01:28:02"
    }
  ]
}            

Also how do i paginate that?

0 likes
3 replies
MaxMatteo's avatar

how about something like this?

Event::with('user') ....

bimalshah72's avatar

@strategicsdemexico

use with('user')

public function index(Request $request)
{
    $events = $this->eventRepo->with('user')->paginate(15);
    if( $request->ajax() ) return $events;
    return view('events.index', compact('events'));
}

in the response, there are two important URL

 "next_page_url": null,
  "prev_page_url": null,

if your records are more than 15, then this will be populated with URLS, which you have to fire for next and previous page. If you need page wise then you need to send 'page" parameter, e.g. hostname/events?page=5

Please or to participate in this conversation.