1

I have a model Publisher that has a many to many relationship to Collection

Both have a property called approved that is set to false when initially created

I have a global scope that hides any Publisher or Collection where approved === false

    public function apply(Builder $builder, Model $model)
    {
        $columnName = $this->tableName ? $this->tableName . '.approved' : 'approved';
        $builder->where($columnName, '=', true);
    }

Publisher is set up as follows:

    public static function boot()
    {
        parent::boot();

        self::creating(function (Publisher $publisher) {
            $publisher->creator_user_id = Auth::user()->id;
        });

        self::created(function (Publisher $publisher) {
            $collection = Collection::create([
                'approved' => (bool)$publisher->approved,
                'title'    => '',
            ]);

            $collection->publishers()->sync($publisher->id);
        });

The problem is that the Collection::create works, but does not return the created Collection when the global scope is applied. It throws the following error:

No query results for model [App\Collection] 12

The 12 is the ID of the Collection created. It is in the DB as expected, so that part works.

I have tried applying withoutGlobalScope(ApprovedScope::class) on the create statement both before and after the create() but that doesn't seem to help.

The weird thing is that $publisher = Publisher::create($request->all()); in my controller does return the created Publisher even though it has the same global scope applied to it

Any ideas?

Update: I have narrowed down the issue and it is caused by Collection using the koenhoeijmakers/laravel-translatable package. So I am still looking for a way to ignore the scope on this create statement.

Surya
  • 129
  • 1
  • 3
  • 12
  • 1
    you need to add the code where you want the collection to be returned. That part is missing from your question. If collection::create() is working the issue is when fetching it. – Christophvh Apr 23 '20 at 11:18
  • I added a line where I sync `Collection` and `Publisher` to the pivot table. I know the problem is when fetching it, but it is fetched as part of the `create` statement. – Surya Apr 23 '20 at 21:48
  • Updated with more info – Surya Apr 25 '20 at 10:05

1 Answers1

0

After careful investigation and some help, it came to light this was the result of the koenhoeijmakers/laravel-translatable package on the Collection

I have solved the issue by not applying the middleware that applies the ApprovedScope on the store routes where this was causing issues.

Surya
  • 129
  • 1
  • 3
  • 12