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

warpig's avatar
Level 12

Am I not allowing input fields in my method?

I am trying to edit a Projects table but at the moment there is a problem with "default values", I @dd() my $project (after my validateProjects()) inside the controller's edit() and I get this:

App\Models\Project {#1005 ▼
  #fillable: array:5 [▶]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: array:1 [▼
    "user_id" => 2
  ]
  #original: []
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}

All it seems to gather is the user_id but the rest of the fields seems to be "gone", I get this error:

General error: 1364 Field 'title' doesn't have a default value

Project.php

    protected $fillable = [
        'user_id',
        'title',
        'description', 
        'display_date',
        'url'
    ];
    public function update(Project $project, Request $request)
    {
        $project['user_id'] = auth()->id();
        
        $project->update($this->validateProject($request));

        dd($project);
        
        $project->save();
        
        return redirect('/projects')->with('edit_project', 'Project edited, cool!');

    }

    protected function validateProject($request) 
    {
        return $request->validate([
            'title' => ['required'],
            'description'  => ['required'],
            'display_date'  => ['required'],
            'url' => ['url'],
        ]);
    }
0 likes
30 replies
Sinnbeck's avatar

What if you remove $project['user_id'] = auth()->id(); and do

return $request->validate([
            'title' => ['required'],
            'description'  => ['required'],
            'display_date'  => ['required'],
            'url' => ['url'],
        ]) + ['user_id' =>auth()->id()];

And refresh dd($project->refresh())

warpig's avatar
Level 12

@Sinnbeck 'user_id' now doesn't have a default value..

        Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->string('title');
            $table->text('description');
            $table->string('display_date');
            $table->string('url')->nullable();
            $table->timestamps();
            $table->timestamp('published_at')->nullable();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        }); 

@sinnbeck if you wanted to know what I get in response from the dd:

App\Models\Project {#1005 ▼
  #fillable: array:5 [▶]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}
Sinnbeck's avatar

Try this

$project->user_id = auth()->id();
$project->fill($this->validateProject($request));
$project->save();
        dd($project);
         
Sinnbeck's avatar

If this does not work as expected, show the route

warpig's avatar
Level 12

This was creating a new record instead of updating the existent one:

$project->user_id = auth()->id();
$project->fill($this->validateProject($request));
$project->save();
        dd($project);

And this worked, we just needed to get the Model first, and then fire up the rest of your code and worked.

    public function update(Project $project, Request $request, $title)
    {   
        $project = Project::where('title', $title)->first();

        $project->fill($this->validateProject($request));
        
        $project->save();

        return redirect('/projects')->with('edit_project', 'Project edited, cool!');
    }

    protected function validateProject($request) 
    {
        return $request->validate([
            'title' => ['required'],
            'description'  => ['required'],
            'display_date'  => ['required'],
            'url' => ['url'],
        ]) + ['user_id' =>auth()->id()];
    }
Sinnbeck's avatar

@warpig the point of the model you are passing in is to use it, as it's bound (loaded from database). Show your route please

warpig's avatar
Level 12

@Sinnbeck ok

    Route::put('/projects/{title}', [ProjectController::class, 'update'])->name('projects.update');
Sinnbeck's avatar

@warpig uhh. Why not find it by id? That's what they are for. Send in the id in the form url

Route::put('/projects/{project}', [ProjectController::class, 'update'])->name('projects.update');
warpig's avatar
Level 12

@Sinnbeck ahh ok.. EDIT @sinnbeck it creates a new record,

        <form
            action="/projects/{{ $project->id }}"
            method="POST"
        >
            @method('PUT')
            @include('projects.form', [
                'submitButtonText' => 'Update Project',
            ])
        </form>
    public function update(Project $project, Request $request, $title)
    {   
        $project->user_id = auth()->id();
        $project->fill($this->validateProject($request));
        $project->save();

        // dd($project);
        return redirect('/projects')->with('edit_project', 'Project edited, cool!');
    }

    protected function validateProject($request) 
    {
        return $request->validate([
            'title' => ['required'],
            'description'  => ['required'],
            'display_date'  => ['required'],
            'url' => ['url'],
        ]);
    }
Sinnbeck's avatar

@warpig great. Now we are getting somewhere.

Check the url in the browser to see if it has the correct ID in the url. And dd in the beginning of the controller method to see if you get the record

public function update(Project $project, Request $request) //deleted title here
    {
        dd($project);
        $project->user_id = auth()->id();
warpig's avatar
Level 12

@Sinnbeck uhmmmm okay...

App\Models\Project {#1005 ▼
  #fillable: array:5 [▶]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}
Sinnbeck's avatar

@warpig I mean the url in the html. Right click the form and click inspect element. Then check the url there

Sinnbeck's avatar

@warpig yup. Perfect. It is correct. Weird. Can you show the update method as it looks currently? :)

1 like
warpig's avatar
Level 12

@Sinnbeck

    public function update(Project $project, Request $request)
    {   
        $project->user_id = auth()->id();
        $project->fill($this->validateProject($request));
        $project->save();

        // dd($project);
        return redirect('/projects')->with('edit_project', 'Project edited, cool!');
    }
Sinnbeck's avatar

@warpig can you try adding the dd as the first line like this?

public function update(Project $project, Request $request)
    {   
        dd($project);
        $project->user_id = auth()->id();
        $project->fill($this->validateProject($request));
        $project->save();

        // dd($project);
        return redirect('/projects')->with('edit_project', 'Project edited, cool!');
    } 
warpig's avatar
Level 12

@Sinnbeck

App\Models\Project {#1005 ▼
  #fillable: array:5 [▼
    0 => "user_id"
    1 => "title"
    2 => "description"
    3 => "display_date"
    4 => "url"
  ]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}
Tray2's avatar

@warpig What happens if you do this in the update method?

$project = Project::findOrFail($request->id);
dd($project, $request);
warpig's avatar
Level 12

@Tray2 hey, nice to see ya!

App\Models\Project {#598 ▼
  #fillable: array:5 [▶]
  #connection: "mysql"
  #table: "projects"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: array:9 [▼
    "id" => 1
    "user_id" => 1
    "title" => "voluptatum"
    "description" => "Et sed et voluptatem enim amet quam autem. Dicta quo excepturi eius sit. Excepturi ratione et neque cum. Ea harum nihil eius sint."
    "display_date" => "February 20, 1992"
    "url" => "https://www.herzog.com/et-tempora-aperiam-eius-delectus-autem-architecto-saepe"
    "created_at" => "2021-12-04 18:38:47"
    "updated_at" => "2021-12-04 18:38:47"
    "published_at" => null
  ]
  #original: array:9 [▼
    "id" => 1
    "user_id" => 1
    "title" => "voluptatum"
    "description" => "Et sed et voluptatem enim amet quam autem. Dicta quo excepturi eius sit. Excepturi ratione et neque cum. Ea harum nihil eius sint."
    "display_date" => "February 20, 1992"
    "url" => "https://www.herzog.com/et-tempora-aperiam-eius-delectus-autem-architecto-saepe"
    "created_at" => "2021-12-04 18:38:47"
    "updated_at" => "2021-12-04 18:38:47"
    "published_at" => null
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}
Illuminate\Http\Request {#44 ▼
  #json: null
  #convertedFiles: []
  #userResolver: Closure($guard = null) {#229 ▶}
  #routeResolver: Closure() {#245 ▶}
  +attributes: Symfony\Component\HttpFoundation\ParameterBag {#46 ▶}
  +request: Symfony\Component\HttpFoundation\InputBag {#45 ▶}
  +query: Symfony\Component\HttpFoundation\InputBag {#52 ▶}
  +server: Symfony\Component\HttpFoundation\ServerBag {#48 ▶}
  +files: Symfony\Component\HttpFoundation\FileBag {#49 ▶}
  +cookies: Symfony\Component\HttpFoundation\InputBag {#47 ▶}
  +headers: Symfony\Component\HttpFoundation\HeaderBag {#50 ▶}
  #content: null
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/projects/1"
  #requestUri: "/projects/1"
  #baseUrl: ""
  #basePath: null
  #method: "PUT"
  #format: null
  #session: Illuminate\Session\Store {#258 ▶}
  #locale: null
  #defaultLocale: "en"
  -preferredFormat: null
  -isHostValid: true
  -isForwardedValid: true
  -isSafeContentPreferred: null
  basePath: ""
  format: "html"
}
warpig's avatar
Level 12

@Sinnbeck i know it is.. how come the Model can't be used inside the method, it's not like an extra query to the database is performed, as far as I know, but perhaps you know better.

This is the route

    Route::put('/projects/{id}', [ProjectController::class, 'update'])->name('projects.update');
Sinnbeck's avatar

@warpig there we go. It needs the name of the variable to match

Route::put('/projects/{project}', [ProjectController::class, 'update'])->name('projects.update'); 
warpig's avatar
Level 12

@Sinnbeck can you check if something is wrong here?

public function update(Project $project, Request $request)
    {   
        $project->user_id = auth()->id();
        $project->fill($this->validateProject($request));
        $project->save();

        // dd($project);
        return redirect('/projects')->with('edit_project', 'Project edited, cool!');
    }
Route::put('/projects/{project}', [ProjectController::class, 'update'])->name('projects.update'); 
        <form
            action="/projects/{{ $project->id }}"
            method="POST"
        >
            @method('PUT')
            @include('projects.form', [
                'submitButtonText' => 'Update Project',
            ])
        </form>
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@warpig now it's correct. But I don't assume that it should ever change user? If not you already have the user_id set, and can simply do this

public function update(Project $project, Request $request)
    {   
        
        $project->update($this->validateProject($request));

        // dd($project);
        return redirect('/projects')->with('edit_project', 'Project edited, cool!');
    }

//and route
Route::put('/projects/{project}', [ProjectController::class, 'update'])->name('projects.update');  
1 like
warpig's avatar
Level 12

@Sinnbeck oof! finally, that is correct, the authenticated user can only update the project.

Sinnbeck's avatar

@warpig awesome. If everything works, consider marking a best answer to set the thread as solved

1 like
warpig's avatar
Level 12

@Sinnbeck sure, I just have to look which one was the best from the discussion to highlight it, it kind of went everywhere, for me, but where do you think the best answer is?

Please or to participate in this conversation.