F
Filament16mo ago
bellini

Basic question regarding relationships in a resource

I have a Post resource, that has a user_id column, and in my form method I have this array:
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\TextInput::make('title')
->required()
->maxLength(255),
Forms\Components\Textarea::make('content')
->required()
->minLength(5),

]);
}
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\TextInput::make('title')
->required()
->maxLength(255),
Forms\Components\Textarea::make('content')
->required()
->minLength(5),

]);
}
How can I automatically save the current authenticated user in the user_id? I have searched the documentation and tried it on the CreatePost class with the mutateFormDataBeforeCreate method but sill doesn't work.
4 Replies
christmex
christmex16mo ago
Hi mate, try this one inside your related model create this function
public function setUserIdAttribute($value)
{
$this->attributes['user_id'] = auth()->id();
}
public function setUserIdAttribute($value)
{
$this->attributes['user_id'] = auth()->id();
}
Let me know if you found any issues Cheers!
ejoi8
ejoi816mo ago
You also can try by using Laravel Events and insert it to your related model.
protected static function booted(): void
{
static::creating(function (User $user) {
if (auth()->hasUser()) {
$user->user_id = auth()->user()->id;
}
});
}
protected static function booted(): void
{
static::creating(function (User $user) {
if (auth()->hasUser()) {
$user->user_id = auth()->user()->id;
}
});
}
bellini
belliniOP16mo ago
Hey thanks for your help, I have tried that but did not work thanks I went with this
Want results from more Discord servers?
Add your server