Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel adding a global condition on an eloquent

I get the invoices in multiple pages using a single query.

Query Code:

$invoices = ImportInvoice::withSupplier() -> withCreatedByAndUpdatedBy() -> orderedName() -> paginate(10);

PROBLEM:

I have added approve field in database which is boolean value weather the invoice is approve (1) or not approve (0).

So now I have to add where('approve', 1) to get the approved invoices.

Problem is that I will edit this eloquent in multiple controllers.

Question is:

Is there a way to add this where condition in the model? Plus sometimes I want to return the Not Approved invoices.

It is similar to Soft Delete created by Laravel.

Soft delete does not get returned when calling a query but if I want to call it I just call withTrashed() function.

like image 977
AE1995 Avatar asked Dec 23 '22 22:12

AE1995


1 Answers

yes you can do like that open your ImportInvoice Model

first import(add) this class ..

use Illuminate\Database\Eloquent\Builder;

and add this boot method

 protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('approve', function (Builder $builder) {
            $builder->where('approve',  1);
        });
    }

now by default get approved invoices

 ImportInvoice::get()

and you want to Approved and Not Approved invoices then do like that

ImportInvoice::withoutGlobalScope('approve')->get();

for more information read this article

like image 67
Jignesh Joisar Avatar answered Jan 05 '23 06:01

Jignesh Joisar