Search code examples
laravelooprelation

transfer the same relation to the core


i have CoreModel extends from Model

class CoreModel extends Model
{

and I extended all the models from coreModel

class Product extends CoreModel

most tables have an author_id column that belongsTo with User

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('author_id')->constrained('users')

inside each model I have to create

public function author(): BelongsTo
{
    return $this->belongsTo(User::class, 'author_id');
}

I need something like that. this relationship ni I need to move to coreModel but it should work with condition if this model has author_id in protected $fillable

What do you advise to do ?

I was thinking about writing trait .but I still have to do it on every model use this trait


Solution

  • I also used Trait as said @Bulent

    trait Author
    {
        /**
         * adding author_id
         * @return void
         */
        protected static function bootAuth(): void
        {
            static::creating(function ($query) {
                $query->author_id = $query->author_id ?? auth()->id();
            });
        }
    
        public function author()
        {
            return $this->belongsTo(User::class, 'author_id');
        }
    }
    

    .

    class Category extends Model
    {
        use Author;