Home > Back-end >  Laravel model - CRUD only with records where one column = certain value?
Laravel model - CRUD only with records where one column = certain value?

Time:04-30

Suppose i have a laravel model that works with a certain (MySQL) database table.

Inside of this table there is a column named 'administration'. (example: could be 1, 2 or 3)

At the moment in my controller im using that modal with eloquent and inside of my eloquent statement i ask only to work with records (crud style) that have administration 2 for instance.

I think it should be possible to add 'where administration = x' to my model instead of my controller so that if i use the model in my controller i would just be dealing with records that have that administration set.

Is this possible? I have tried googling it but could not find an answer yet.

CodePudding user response:

Laravel uses global scopes for this.

You would create a scope for the administration:

<?php
 
namespace App\Scopes;
 
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
 
class AdministrationScope 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('administration', '=', 2);
    }
}

And then you add it as a global scope to the model

<?php
 
namespace App\Models;
 
use App\Scopes\AdministrationScope;
use Illuminate\Database\Eloquent\Model;
 
class YourModel extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope(new AdministrationScope);
    }
}
  • Related