The task is as follows: In the view you need to display the previous news. The decision to write a function in the model

public function getPrevious() { $postID = self::where('id', '<', $this->id)->max('id'); //ID return self::find($postID); } 

with a sample of the base. The problem when displaying in the view, you need to write there

 {{$post->getPrevious()->title}} {{$post->getPrevious()->slug}} {{$post->getPrevious()->img}} 

It turns out 3 sql request. How to find a beautiful solution without resorting to declaring a variable in a view?

    1 answer 1

    And how do you imagine that you need to save the value and not use the variable? You can do this:

     public function getPrevious() { if (!isset($this->previous)) { $this->previous = self::where('id', '<', $this->id)->orderBy('id', 'desc')->first(); // firstOrFail Ρ‚Π°ΠΊ ΠΆΠ΅ ΠΌΠΎΠΆΠ½ΠΎ, зависит ΠΎΡ‚ вашСй Π»ΠΎΠ³ΠΈΠΊΠΈ. } return $this->previous; } 
    • By the way, thanks for not having thought of it myself. I meant without creating a variable in the template itself. #php $ result = $ post-> getPrevious (); #endphp {{$ result-> title}} {{$ result-> img}} - Alisher-ea