With Eloquent models adding scopes is easy:
public function scopeMyScope($query)
{
// Do stuff to that $query
}
But how to add scope to
DB::table
doesn't have support for scopes. What you could do is simply write a little function that does some things with the query and returns it. The syntax isn't as nice but it works:
function applyScope($query){
$query->whereNotNull('deleted_at');
$query->where('foo', 'bar');
return $query;
}
And then:
$query = DB::table('page_views')
->where('id', $this->id)
->where('agent', 'NOT LIKE', '%bot%');
$query = applyScope($query);
$views = $query->count(DB::raw('distinct session, DATE(created_at)'));
Or a bit a shorter syntax:
$views = applyScope( DB::table('page_views')
->where('id', $this->id)
->where('agent', 'NOT LIKE', '%bot%')
)->count(DB::raw('distinct session, DATE(created_at)'));