Search previous and next record of the selected one in laravel 5.3 [closed]

0

How can I get the previous record and the one that follows from the selected record.

example: I have the record 2 but I want me to find the 1 and the 3. How can I find it in eloquent?

    
asked by DeCo 27.12.2016 в 19:11
source

2 answers

2

in the model you can create a couple of functions to bring them:

public function siguiente(){
    return Modelo::where('id', '>', $this->id)->orderBy('id', 'asc')->first();
}

public function previo(){
    return Modelo::where('id', '<', $this->id)->orderBy('id', 'desc')->first();
}
    
answered by 27.12.2016 / 20:13
source
0

first of all I imagine that you have the id of the record, what you can do very simply is to add a sentence of type "whereIn" A basic example would be that you have the id number 2, with a subtraction and a sum you know what you need, the statement asks that the values be stored in an array [] you could pass it in the following way or in a variable.

->whereIn('id', [1,3])
->get();

With this you will get what you need, greetings.

Indeed my estimate now if I understand your question, what you could do is get the results you are looking for in the following way,

select id from tabla where tabla.id < (id que tienes) order by id desc limit 1
select id from tabla where tabla.id > (id que tienes) order by id asc limit 1

This way you get the values you need, so the query would be the only thing you would have to do is rewrite it with laravel.

    
answered by 27.12.2016 в 19:51