Last active
December 12, 2018 22:12
-
-
Save brayniverse/fb1b58d20bdfba07e822153d7edb592a to your computer and use it in GitHub Desktop.
Custom Eloquent query builders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Post extends Model | |
{ | |
/** | |
* Create a new Eloquent query builder for the model. | |
* | |
* @param \Illuminate\Database\Query\Builder $query | |
* @return \Illuminate\Database\Eloquent\Builder|static | |
*/ | |
public function newEloquentBuilder($query) | |
{ | |
return new PostQueryBuilder($query); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Builder; | |
class PostQueryBuilder extends Builder | |
{ | |
/** | |
* Filter out unpublished posts. | |
* | |
* @return \App\PostQueryBuilder|\Illuminate\Database\Eloquent\Builder | |
*/ | |
public function published() | |
{ | |
return $this->whereNull('published_at'); | |
} | |
/** | |
* Get the 5 most popular posts. | |
* | |
* @return \App\PostsCollection | |
*/ | |
public function popular() | |
{ | |
return $this | |
->where('likes', '>', 100) | |
->take(5) | |
->orderByDesc('likes') | |
->get(); | |
} | |
/** | |
* Get the latests published post. | |
* | |
* @return \App\Post | |
*/ | |
public function mostRecent() | |
{ | |
return $this->published()->latest('published_at'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
class PostsController extends Controller | |
{ | |
public function index() | |
{ | |
return view('posts', [ | |
'posts' => auth()->user()->posts()->published(), | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment