PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 2, 2022

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

 January 02, 2022     laravel, laravel-5.5, scope     No comments   

Issue

I have multiple models, all with timestamps. I'm often using whereDate to get all rows from today and yesterday, like this:

ModelName::whereDate('created_at', now()->today())->get();
ModelName::whereDate('created_at', now()->yesterday())->get();

I want to have it shorter, simplier, like:

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

I can not find any methods to do this, so I found in documentation that I can make own "scopes". The problem is, that I can make it for specified model, but I can not find a way to make it globally, for all models. Now I need to paste this scope methods in every model class. This works, but I need to repeat this code in every model class, so it's not a good way to do this I'm sure.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ModelName extends Model
{


    /**
     * Custom scope (query builder method) to easy return all items from today
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeToday($query)
    {
        return $query->whereDate('created_at', now()->today());
    }


    /**
     * Custom scope (query builder method) to easy return all items from yesterday
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeYesterday($query)
    {
        return $query->whereDate('created_at', now()->yesterday());
    }
}

Solution

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.



Answered By - Alexey Mezenin
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing