Laravel Global Scope apply function runs twice

196 views Asked by At

I'm new to Laravel and struggling with a problem. I created a globalScope for a model named "Contact". This model belongs to another model called "Company".

When the globalScope is applied to the Contact model, whatever I add inside the globalScope runs twice. If I echo "red" inside it, the result is "redred". Does anyone have any thoughts on this?

Contact model code is here

<?php

namespace App\Models;

use App\Scopes\sampleScope;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    protected static function booted()
    {
        static::addGlobalScope(new sampleScope);
    }

}

Here is the globalscope code

<?php
namespace App\Scopes;

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

class sampleScope implements Scope
{

    public function apply(Builder $builder, Model $model)
    {   
        echo "red";
    }

}

This is what I get on the front-end. Is there a reason why this is repeated twice?

0

There are 0 answers