Ad

Get Data From Model With Condition Laravel 5.7

- 1 answer

I have Users_group model in my Laravel project.

Code:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class Users_group extends Model
{
    use Notifiable;

    protected $table = 'users_groups';
    protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];

    public function getGroupData()
    {
        return $this->hasOne('App\Group','id','group_id');
    }
}

And when I want to get data from this model I use this my custom method:

$data = App\Users_group ::get();

It's working great

I want to get the data from model with condition not like this:

$data = App\Users_group::where('group_id','>',5)->get();

I need to put the condition inside the model file thats make the model return the data everytime I call User_group::get() return it when condition inside the model.

Thanks!

Ad

Answer

You can use query scopes to achieve this. Query scopes allow you to add a global constraint to a model.

In your case, you could add the following boot method to your model:

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

    static::addGlobalScope('groupOver5', function (Builder $builder) {
        $builder->where('group_id', '>', 5);
    });
}
Ad
source: stackoverflow.com
Ad