Bilal Arshad
Bilal Arshad

Reputation: 571

How to set where condition globally on model in laravel?

I am fething Data from database with the help of this query

Staff::where('active',1)->get()

I am using this query in many places in my project is it possible to use this where condition globally? in the model so I don't have to change it everywhere

Upvotes: 0

Views: 1516

Answers (3)

Shakil Ahmmed
Shakil Ahmmed

Reputation: 128

Using Global Scope:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class ActiveScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('active', 1);
    }
}

In Your Model :

<?php

namespace App\Models;

use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Model;

class Staff extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope(new ActiveScope);
    }
}

Or You Can Use Local scope Query :

<?php
    
    namespace App\Models;
    use Illuminate\Database\Eloquent\Model;
    
    class Staff extends Model
    {
         
       public function scopeActive($query)
       {
          return $query->where('active',1);
       }
    }

In Your Controller :

Staff::active()->get();

Upvotes: 0

Yudiz Solutions
Yudiz Solutions

Reputation: 4449

In Staff Model :-

class Staff extends Model
{
    public function scopeActive($q)
    {
        return $q->where('is_active','y');
    }

}

In Controller:-

$staffs= Staff::active()->get();

$staff= Staff::active()->find(1);

Upvotes: 0

knubbe
knubbe

Reputation: 1182

You can use scope for that. Check this doc ;) This is your example

Upvotes: 1

Related Questions