Todo Laravel Project - Handling update request

Laravel Project

Share

In this Laravel project tutorial we will learn to handle update request.

In the previous tutorials we have covered how to fetch todo task by id and we also created the edit form for the todo tasks.

Now, we will configure the update route and TodoController to handle the update request.

The updateTodoById method

Open the TodoController.php file which is inside the app/Http/Controllers directory and add the updateTodoById() method.

public function updateTodoById($id, Request $request)
{
  $request['id'] = $id;
  return $request;
}

For now we will append the $id and return the submitted $request.

Configure the route

Open the routes/web.php file and set the update todo tasks route.

Route::put('/todo/{id}', 'TodoController@updateTodoById');

So, when the Edit form is submitted the updateTodoById method of the TodoController class will be called and the {id} will be passed as a parameter along with the submitted data to the $request variable.

So, if we now open any todo task in the edit page and submit the form we will get to see the submitted data in JSON form like the following.



Alright, time to write the logic to handle the submitted data and save it in the database.

Update logic

Write the following code in the updateTodoById() method to handle the update data and save the changes in the database.

public function updateTodoById($id, Request $request)
{
  // $request['id'] = $id;
  // return $request;

  // validate
  $validatedData = $request->validate([
    'todo-title' => 'required|max:100',
    'todo-description' => 'required|max:5000',
    'todo-status' => 'required'
  ]);

  // find
  $todo = Todo::find($id);

  // set data
  if (isset($request['todo-title'])) {
    $todo->title = $request['todo-title'];
  }
  if (isset($request['todo-description'])) {
    $todo->description = $request['todo-description'];
  }
  if (isset($request['todo-status'])) {
    $todo->status = $request['todo-status'];
  }

  // update
  $todo->update();

  // redirect to todo/id page
  return redirect('/todo/' . $id);
}

In the above code we are first validating the submitted data.

Then we are fetching the todo task for the given id.

Next we are setting the submitted title, description, status data.

Finally, we are updating the data and redirecting to the same page.

If we now edit any todo task and submit the data it will be updated in the database.



Alright, we are now handling the update request. In the next tutorial we will be working with the delete request.

So, I will see you in the next tutorial. Have fun coding :-)

Share