<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as EloquentModel;
class Model extends EloquentModel
{
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->perPage = request()->per_page ?? 15;
}
protected static function boot()
{
parent::boot();
static::addGlobalScope('defaultSort', function (Builder $builder) {
$builder->orderByDesc('id');
});
}
public function scopeRecent($query)
{
return $query->orderBy('updated_at', 'desc');
}
public function scopeFilter($query, $filters)
{
foreach ($filters as $k => $v) {
if (is_array($v)) {
$query->whereIn($k, $v);
} else {
$query->where($k, $v);
}
}
}
public function scopeEarlierThan($query, $column, $ended_at)
{
if (isset($ended_at)) {
$query->where($column, '>=', $ended_at);
}
}
public function scopeLaterThan($query, $column, $started_at)
{
if (isset($started_at)) {
$query->where($column, '<=', $started_at);
}
}
}
...
public function get(Request $request)
{
$filters = $request->only('id', 'title');
$posts = Post::filter($filters)->get();
}
...