Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom methods to Eloquent Model in Laravel

I have an Eloquent Article model in my Laravel 4 app. It's empty at the moment, but what I want to do is define two methods:

  • getNextArticle
  • getPreviousArticle

So that when I use:

$article = Article::find(1);

I can follow up with:

$article->getNextArticle;

and

$article->getPreviousArticle;

I need to get access to the results returned from find() within the Articles model so I can use the data to get the next and previous articles from an SQL query.

Theoretically I end up with something like:

class Article extends Eloquent
{
    public function getNextArticle()
    {
        // SQL query to get next article from the database
    }

    public function getPreviousArticle()
    {
        // SQL query to get previous article from the database
    }
}
like image 404
James Jeffery Avatar asked Jun 28 '13 18:06

James Jeffery


2 Answers

Class Article extends Eloquent {

    public function getNextArticle()
    {
        return Article::where('id', '>', $this->id)->take(1)->get();
    }

    public function getPreviousArticle()
    {
        return Article::where('id', '<', $this->id)->take(1)->get();
    }
}
like image 195
deyes Avatar answered Nov 11 '22 14:11

deyes


Source Laravel http://laravel.com/docs/4.2/eloquent

Article is redundant so i removed it.

Class Article extends Eloquent {

        public function scopeNext($query)
        {
            return $query->where('id', '>', $this->id)->take(1)->get();
        }

        public function scopePrevious($query)
        {
            return $query->where('id', '<', $this->id)->take(1)->get();
        }
    }
like image 25
ronscript Avatar answered Nov 11 '22 15:11

ronscript