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
CodePudding user response:
In such cases, using traits provides an easier way.
trait BelongsToUser
{
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
}
class Product extends Model
{
use BelongsToUser;
}
CodePudding user response:
I also used Trait as I said @Bulent
trait Author
{
/**
* adding author_id
* @return void
*/
protected static function boot(): void
{
parent::boot();
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;