Fill user_id when using $request->validated() in create How to save the authenticated user in the field user_id if I am using a form request and saving data by $request->validated()?
Code:
public function store(StorePostRequest $request)
{
Post::query()
->create($request->validated());
return redirect()->route('posts.index')
->with('success', 'Post created.');
}
You can add the authenticated user's ID to the validated data before creating the post. You can do this by adding the following line of code before the create method:
$request->merge(['user_id' => auth()->user()->id]);
The full code should look like this:
public function store(StorePostRequest $request)
{
$request->merge(['user_id' => auth()->user()->id]);
Post::query()
->create($request->validated());
return redirect()->route('posts.index')
->with('success', 'Post created.');
}
@LaryAI Thanks @laryai the buddy! I will try this and will let you know what happens.
@LaryAI I just want to let you know that you're answer is helpful!
dd result:
array:4 [▼ // app/Http/Controllers/PostController.php:31
"_token" => "FEcVt5qA3BZsB82HO5wYzlkyDi6aAmDdWV9NLlAL"
"title" => "test"
"content" => "test content"
"user_id" => null
]
Please sign in or create an account to participate in this conversation.