Pixelairport's avatar

Default where() for all model actions

I created a application where we show projects. Now everything is ready to go live and on person said he wants to have test projects only seen by the team members. ... Problem is that we have a lot of different listings, we also cache like Projects::lastMonth(), ...

I now created a field called 'hide' which can have 0 or 1... Is it possible to say in laravel that the model should ever just call hide=0 ... I mean when i use get() or first() and things like that. And only when i say where(hide, 1) then call also 1?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

One solution to this problem is to use global scopes in Laravel. Global scopes allow you to define constraints that are automatically applied to all queries for a given model. In this case, we can define a global scope that adds a "where" clause to all queries for the "Project" model that filters out any projects with "hide" set to 1.

Here's an example of how to define a global scope for the "Project" model:

<?php

namespace App\Scopes;

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

class HideScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('hide', 0);
    }
}

This global scope adds a "where" clause to all queries for the "Project" model that filters out any projects with "hide" set to 1.

To use this global scope, we need to register it with the "Project" model. We can do this by adding the following code to the "Project" model:

<?php

namespace App;

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

class Project extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new HideScope);
    }
}

This code registers the "HideScope" global scope with the "Project" model.

Now, whenever we query the "Project" model using methods like "get" or "first", the global scope will automatically add a "where" clause that filters out any projects with "hide" set to 1.

If we want to include the hidden projects in a query, we can use the "withoutGlobalScope" method to temporarily disable the global scope. For example:

$projects = Project::withoutGlobalScope(HideScope::class)->get();

This code retrieves all projects, including those with "hide" set to 1, by temporarily disabling the "HideScope" global scope.

Note that global scopes are applied to all queries for a given model, so if you have other queries that need to include hidden projects, you'll need to use the "withoutGlobalScope" method to disable the global scope for those queries.

Please or to participate in this conversation.