I have a comments model that has both a polymorphic relationship(to Tasks and Projects) and a relationship to the User model.
I wonder if there is a nice way to create a comment and also create a relationship to the User model without adding the user_id to the fillable fields of the Task model.
To illustrate, the comment can be created via the polymorphic relation:
$task->comments()->create(['body' => 'foo']);
But I would also like to set the 'user_id' of the comment to the currently signed-in user. Can this be done without adding the user_id to the fillable fields of the Comment model and pass it into the create() method?
Yes, you can set the 'user_id' of the comment to the currently signed-in user without adding the user_id to the fillable fields of the Comment model and pass it into the create() method. You can use the 'associate' method to create the relationship between the comment and the user. Here's an example:
// Get the currently signed-in user
$user = auth()->user();
// Create the comment via the polymorphic relation
$comment = $task->comments()->create(['body' => 'foo']);
// Associate the comment with the user
$comment->user()->associate($user);
// Save the comment
$comment->save();
This code assumes that you have defined the 'user' relationship on the Comment model like this:
public function user()
{
return $this->belongsTo(User::class);
}