简体   繁体   中英

Laravel 5.4 update method

I am trying to update the record in the database. This is a specific element that is an element of another. Here is my code, it doesnt work :/

web.php :

 Route::patch('/projects/{projectID}/{id}', 'ProjectsController@update');

Controller:

public function update($projectId, $id, CreateProjectRequest $request)
    {
        $page = Page::findOrFail($id);
        $page->update([
           'name' => $request->name,
       ]);

       return redirect('/projects/' . $projectId);
    }

HTML:

{!! Form::model($page, ['method'=>'PATCH', 'action' => {!! Form::model($page, ['method'=>'PATCH', 'action' => ['ProjectsController@update', $project->id, $page->id]]) !!}

  {!! Form::text('name',null,['class'=>'blue-inp']) !!}

 {!! Form::submit('Save changes',['class'=>'btn btn-save-blue']) !!}

 {!! Form::close() !!}

You need to switch the class type-hint CreateProjectRequest for just Request in your controllers update method.

The variables passed from the form input fields can then be accessed like this:

$name = $request->input('name');

More on the topic: https://laravel.com/docs/5.0/requests

You can simplify the controller method, assuming the CreateProjectRequest handled all the necessary validation and it's inputs match the inputs you want to update Edit: I prefer to validate everything with formrequests with rules and by the time it reaches the controller, it just calls services or does stuff. As far as naming conventions, you may not need to send the $id in the url parameter and send it within the body, in order to avoid using Request in the formrequest to validate if it exists in the database

public function update($projectId, $id, CreateProjectRequest $request)
{
    $data = $request->validated();
    Page::findOrFail($id)->update($data);

    return redirect('/projects/' . $projectId);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM