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
}
}
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();
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With