Search code examples
phplaraveleloquentlaravel-11

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?


Solution

  • 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 the auth middleware, and therefore Auth::id() will always contain the valid id of the currently logged in user, and should be merged after the validation

    // make sure this route has the auth middleware
    public function store(PdlocationStoreRequest $request): RedirectResponse
        {
            // all the fields including user_id should be in the model's $fillable attribute
            Pdlocation::create([...$request->validated(), 'user_id' => Auth::id()]);
               
            return redirect()->route('admin.pdlocation.index')
                             ->with('success', 'Pdlocation created successfully.');
        }