Make custom query builder method (query scope) for all models in Laravel 5.5

喜你入骨 提交于 2019-12-01 09:31:37

You can define the local scopes in a trait:

<?php
namespace App\Traits;

trait Scopes
{
    public function scopeToday($query)
    {
        return $query->whereDate('created_at', now()->today());
    }

    public function scopeYesterday($query)
    {
        return $query->whereDate('created_at', now()->yesterday());
    }
}

Then use the trait in any model you like:

use App\Traits\Scopes;

And to use the traits:

ModelName::today()->get();
ModelName::yesterday()->get();

Another way to do that is to create and extend a base model class and define the scopes there, but I'd use a trait.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!