Laravel previous and next records
Below are your updated controller and view files derived from @ridecar2 link,
Controller:
public function show($id){ // get the current user $user = User::find($id); // get previous user id $previous = User::where('id', '<', $user->id)->max('id'); // get next user id $next = User::where('id', '>', $user->id)->min('id'); return View::make('users.show')->with('previous', $previous)->with('next', $next);}
View:
<a href="{{ URL::to( 'users/' . $previous ) }}">Previous</a><a href="{{ URL::to( 'users/' . $next ) }}">Next</a>
// in your model filepublic function next(){ // get next user return User::where('id', '>', $this->id)->orderBy('id','asc')->first();}public function previous(){ // get previous user return User::where('id', '<', $this->id)->orderBy('id','desc')->first();}// in your controller file$user = User::find(5); // a clean object that can be used anywhere$user->next();$user->previous();
I understand the approach being taken here by user2581096 but I am not sure it is efficient (by any standards). We are calling the database 3 times for really no good reason. I suggest an alternative that will be way more efficient and scalable.
Do not pass the previous and next IDs to the view. This eliminates 2 unnecessary database calls.
Create the following routes:
users/{id}/next
users/{id}/previous
These routes should be used in the href attributes of the anchor tags
Add methods in the controller to handle each of the new routes you have created. For example:
public function getPrevious(){ // get previous user $user = User::where('id', '<', $this->id)->orderBy('id','desc')->first(); return $this->show($user->id); }
This function will only be called when you actually click on the button. Therefore, the database call is only made when you need to actually look up the user.