One solution to this problem is to override the validated method in the form request class to merge the user_id field before returning the validated data. Here's an example:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePostRequest extends FormRequest
{
public function rules()
{
return [
'title' => 'required|string|max:255',
'content' => 'required|string',
];
}
public function validated()
{
$data = parent::validated();
$data['user_id'] = auth()->user()->id;
return $data;
}
}
In this example, we're extending the FormRequest class and overriding the validated method. We first call the parent validated method to get the validated data, and then we merge the user_id field with the authenticated user's ID. Finally, we return the merged data.
Now, when we call $request->validated() in the controller's store method, the user_id field will be included in the validated data:
public function store(StorePostRequest $request)
{
Post::query()
->create($request->validated());
return redirect()->route('posts.index')
->with('success', 'Post created.');
}