Home > Software engineering >  apply filter to the laravel model
apply filter to the laravel model

Time:08-16

I have a PHP laravel forum application. The application has a Question model below:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    protected $fillable = [
        'title', 'question'
    ];
    
    public function user()
    {
        return $this->belongsTo("App\User")->whereNull('deleted_at');
    }

}

The issue is that when the user is soft deleted (deleted_at is not null), the model Question::find() still finds some cases associated with the soft deleted users. In fact, it should return null. My understanding is that there should be a join somewhere in the model to filter out any result that users.deleted_at is not null that I tried but I do not think that this is the right way of doing that. Can someone please comment on this?

CodePudding user response:

If you want to get only questions with not deleted users everywhere in your system you have to use Global Scopes.

There are two ways of creating global scopes. The easiest way is to put the following code block into your Question model and check the output.

protected static function booted()
{
    static::addGlobalScope('activeUsers', function (Builder $builder) {
        $builder->whereHas('user', function ($query) {
            $query->whereNull('deleted_at');
        });
    });
}

and keep remembering to use the Builder class

use Illuminate\Database\Eloquent\Builder;

If you like to separate the scope from the model, you can try another method of creating the global scopes. Global Scope - Laravel Documentation

CodePudding user response:

The class should be like this

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Question extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'title', 'question'
    ];
    
    public function user()
    {
        return $this->belongsTo("App\User")->whereNull('deleted_at');
    }

}
  • Related