Skip to content

Instantly share code, notes, and snippets.

@brayniverse
Last active December 12, 2018 22:12
Show Gist options
  • Save brayniverse/fb1b58d20bdfba07e822153d7edb592a to your computer and use it in GitHub Desktop.
Save brayniverse/fb1b58d20bdfba07e822153d7edb592a to your computer and use it in GitHub Desktop.
Custom Eloquent query builders
<?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);
}
}
<?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');
}
}
<?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