1

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?

Nishad
  • 11
  • 4
  • How are you displaying the value in frontend ? – Ravi Sigdel Jul 28 '22 at 17:37
  • I use a view to display the uery details. But even if I disable the view, I see the word "red" repeating twice. I added the globalscope to the Company model to which this model belongs to, and there the word is displayed only once – Nishad Jul 28 '22 at 17:54
  • @Nishad Dit you ever figure this out? I'm having have the same issue. – Ken Oct 17 '22 at 12:20

0 Answers0