The eloquent best way to handle unpublished content

I am trying to deal with the case when the columns in one of my tables have status, which is either draft, or published.

Is there an easy way to indicate somehow in the model that it should only get the publisheddefault tags ?

It would be great if I could draftsalso get with some condition.

+4
source share
2 answers

What you are looking for is called Global Scopes.

You have already seen it in the Soft DeleteTrait form , which uses the global scope to retrieve rows onwhereNull('deleted_at')

, :

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

+3

, , , Query Scopes.

, .

, , :

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

:

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

, , - , . :

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

, :

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

:

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

, , .

+3

Source: https://habr.com/ru/post/1626086/


All Articles