Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

NoLAstNamE's avatar

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.');
}
0 likes
3 replies
LaryAI's avatar
Level 58

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.');
}
1 like
NoLAstNamE's avatar

@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 or to participate in this conversation.