James Jeffery
James Jeffery

Reputation: 12579

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:

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
    }
}

Upvotes: 10

Views: 16499

Answers (3)

ronscript
ronscript

Reputation: 407

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();
        }
    }

Upvotes: 3

deyes
deyes

Reputation: 657

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();
    }
}

Upvotes: 13

Kylie
Kylie

Reputation: 11749

I would probably try it like this... not sure if it would work though

 class Article extends Eloquent
  {
    public function getNextArticle()
    {
    return Article::find($this->id+1)->get();
    }

    public function getPreviousArticle()
    {
    return Article::find($this->id-1)->get();
    }
  }

Upvotes: 0

Related Questions