I’d like to insert the user-id of the current user into a table in column "user_id". The field is a relation to the user table.
Migration / database schema
Schema::create('pdlocations', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->decimal('lon', 10, 7);
$table->decimal('lat', 10, 7);
$table->string('map');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')
->on('users');
});
In the controler (PdlocationController.php)
public function store(PdlocationStoreRequest $request): RedirectResponse
{
$request->merge([
'user_id' => auth()->user()->id,
// 'user_id' => auth()->user(),
]);
$this->validate($request, [
'user_id' => 'required|exists:users,id',
]);
Pdlocation::create($request->validated());
return redirect()->route('admin.pdlocation.index')
->with('success', 'Pdlocation created successfully.');
}
If merging into the request the current userID auth()->user()->id
I get the following error message:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value
insert into
`pdlocations` (`map`, `lon`, `lat`, `updated_at`, `created_at`)
values
(test, 66, 55, 2024 -06 -21 18: 42: 57, 2024 -06 -21 18: 42: 57)
If merging into the request instead the user object auth()->user()
the validator says The selected user id is invalid.
Any idea or suggestion what I’m missing?
2
Answers
I think the main problem here is that
user_id
doesn’t exist in the$fillable
attribute inside the model.Apart from this, what you are trying to do here isn’t really the best, you shouldn’t validate the
user_id
anyways, what you need to do is make sure this route is guarded by theauth
middleware, and thereforeAuth::id()
will always contain the valid id of the currently logged in user, and should be merged after the validationjust use request methods like
to get some of the inputs you can use