bart
bart

Reputation: 15298

Where to place this Eloquent query logic in Laravel 9?

Let's say I have a model Book with a field published that is either true or false and I often need to retrieve books that have been published in the current year. I can create following Eloquent query:

Book::where(['published', true], ['publish_date', date('Y')])->get();

Where should I place this code? In my controller or my model? And how would I call it?

Book->getPublished()
Book::getPublished()

Upvotes: 2

Views: 43

Answers (1)

Kirk Beard
Kirk Beard

Reputation: 9843

Typically you'd use Query Scopes for handling this commonly accessed logic. Add the following method to your Book model:

class Book extends Model
{
    public function scopePublished($query)
    {
        return $query
            ->where('published', true)
            ->where('publish_date', date('Y));
    }
}

You can then use this scope in your code via Book::published()->get().

The benefit of declaring the scope, but not including the ->get() is that you can chain multiple methods when required. For example:

$books = Book::published()->order_by('publish_date')->limit(25)->get();

Upvotes: 2

Related Questions