From 22630c293bb9091541efe1132b1783ecbc949de3 Mon Sep 17 00:00:00 2001 From: Jordan Doyle Date: Sun, 16 Oct 2016 23:03:33 +0100 Subject: [PATCH] publish scope applied by default & findBySlug added --- src/Models/Post.php | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/Models/Post.php b/src/Models/Post.php index 88d5982..41c60ef 100644 --- a/src/Models/Post.php +++ b/src/Models/Post.php @@ -2,7 +2,6 @@ namespace Koselig\Models; use Illuminate\Database\Eloquent\Builder; -use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; @@ -23,6 +22,20 @@ class Post extends Model public $timestamps = false; /** + * The "booting" method of the model. + * + * @return void + */ + protected static function boot() + { + parent::boot(); + + static::addGlobalScope('published', function (Builder $builder) { + $builder->where('post_status', 'publish'); + }); + } + + /** * Get all the posts within a certain post type. * * @param Builder $query query to add the scope to @@ -35,14 +48,14 @@ class Post extends Model } /** - * Get all the posts which are published. + * Get a post by its slug. * - * @param Builder $query query to add the scope to - * @return Builder + * @param $slug + * @return static */ - public function scopePublished($query) + public static function findBySlug($slug) { - return $query->where('post_status', 'publish'); + return static::where('post_name', $slug)->first(); } /** -- libgit2 1.7.2