jeudi 28 mai 2020

Laravel trait except for specific function

I am using Trait for one model in Laravel 7.

namespace App;

use App\Traits\AutoFieldTrait;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class BlogPost extends Model implements HasMedia
{
   use AutoFieldTrait;
   use InteractsWithMedia;

   public function fun1() { ... }

   public function fun2() { ... }

   public function registerMediaConversions(Media $media = null): void
   {
     $this->addMediaConversion('thumb')
        ->width(368)
        ->height(232)
        ->sharpen(10);
   }

}

AutoFieldTrait is to add one additional where clause automatically.

I want it for fun1() and fun2(), but I don't want to it will be applied to registerMediaConversions() .

Is there any way to exclude some functions from trait?


Here is AutoFieldTrait.

<?php

namespace App\Traits;

trait AutoFieldTrait{
    public static function bootAutoFieldTrait()
    {
        static::addGlobalScope(new AutoFieldScope());
    }
}

namespace App\Traits;

use Illuminate\Database\Query\Builder as BaseBuilder;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;

class AutoFieldScope implements Scope {
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('user_id', '=', auth()->user()->id);
    }
}

And registerMediaConversions() is from laravel-medialibrary package.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2TKHjTS
via IFTTT

Aucun commentaire:

Enregistrer un commentaire