chrRtg's avatar

Laravel 11 - validated() and related table

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?

0 likes
3 replies
Snapey's avatar

two things.

Why are you getting the authenticated user's id then checking if is in the users' table? They MUST exist for them to be logged in!

Instead of merging the data, use the user to create the model

Auth::user()->pdlocations()->create($request->validated());

Eloquent will recognise the relationship and automatically insert the user_id

chrRtg's avatar

Got it! I forgot to add the field "user_id" in the $fillable of my model.

sidanalavi's avatar

Even if you haven't added user_id in fillable , you must not use this approach as user is already logged in you and you are checking if it exists, you adding unnecessary cost to each call. You should use the way @snapey suggested or

auth()->user()->pdlocations()->create($request->validated());

PS- both are same auth() is just helper function which does the same thing

Please or to participate in this conversation.