Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent best way to deal with unpublished content

I'm trying to deal with a case where the columns in one of my tables have a status, which is either draft or published.

Is there an easy way to specify somehow in the model that it should only get the published ones by default?

It would be great if I could get the drafts too with some condition.

like image 983
Alex Avatar asked Mar 14 '23 12:03

Alex


2 Answers

I'm not sure quite how to do it by default, but you can do this easily using Query Scopes.

You define these inside your model and then can call them when running your eloquent query.

For example you could set one up like so to get only the published articles:

/**
 * Scope a query to only include published articles.
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopePublished($query)
{
    return $query->where('status', '=', 'published');
}

You can then call this on your eloquent query like this:

$articles = App\Articles::published()->get();

You can chain these too, so if you needed to add any other scopes to the query then you can just add them on. For example:

$articles = App\Articles::published()->orderBy('created_at')->get();

Doing the same for draft articles would be easy and just a case of changing the status you're looking for:

/**
 * Scope a query to only include draft articles.
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeDraft($query)
{
    return $query->where('status', '=', 'draft');
}

Using it like so:

$articles = App\Articles::draft()->get();

Checkout the docs through the link above, as you could also create a dynamic scope and just pass in to it the type of article you were searching for.

like image 20
James Avatar answered Apr 08 '23 04:04

James


What you are looking for is called Global Scopes.

You have previously seen it in the form the Soft Delete Trait which applies a global scope to retrieve rows on whereNull('deleted_at')

Jack has a spot-on article on the subject you wish to tackle:

http://softonsofa.com/laravel-5-eloquent-global-scope-how-to/

like image 63
Mysteryos Avatar answered Apr 08 '23 04:04

Mysteryos