create-todo-app-update-and-delete

Create Todo app with laravel – Update and Delete

Hello World, Welcome to my laravel tutorial series Learn Laravel with example. This is second part of create todo app with laravel. In the previous article, we have learned that how to add and show data with laravel and MySQL. In this article we will extend the previous article. We will perform update and delete operation with laravel in this article.

I have divided this tutorial in the following parts.

Update the Controller File

  • Open TodoController.php  Controller in text editor that you have created in last tutorial and add the following code in it for update and delete.
// Edit Todo
    function edit($id){
        $data=Todo::find($id);
    	return view('update',['todo'=>$data]);
    }

    // Update Todo
    function update(Request $request,$id){
        $todo=Todo::find($id);
        $todo->title=$request->input('title');
        $todo->description=$request->input('desc');
        $todo->save();
        return redirect('todo/edit/'.$id)->with('success', 'Task has been updated!');
    }
    // Delete Todo Task
    function delete($id){
        DB::table('todos')->where('id', $id)->delete();
        return redirect('/')->with('success', 'Task has been deleted!');
    }

Create the View Files

  • Create the edit.blade.php file at the same place where add.blade.php has been created and add the following code.
@extends('common')
@section('title', 'Update Task')
@section('page_heading') 
<h2 class="mb-3">Update Task</h2>
@endsection

@section('content')
<table class="table table-bordered">
	<form action="{{url('todo/update')}}/{{$todo->id}}" method="POST">
	{{ csrf_field() }}
	<tbody>
		@if(Session::has('success'))
		<tr class="bg-success">
			<td colspan="2">
				{{session('success')}}
			</td>
		</tr>
		@endif
		<tr>
			<th colspan="4"><a href="{{url('/')}}" class="btn btn-secondary btn-sm"><< Task List</a></th>
		</tr>
		<tr>
			<th>Title</th>
			<td><input type="text" value="{{ $todo->title }}" class="form-control" name="title" /></td>
		</tr>
		<tr>
			<th>Description</th>
			<td>
				<textarea name="desc" class="form-control" rows="10">{{ $todo->description }}</textarea>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<input type="submit" class="btn btn-danger" />
			</td>
		</tr>
	</tbody>
	</form>
</table>
@endsection

Update the Route file

  • Open the web.php in routes folder and update with the following code.
Route::get('/todo/edit/{id}','TodoController@edit');
Route::post('/todo/update/{id}','TodoController@update');

Route::get('/todo/delete/{id}','TodoController@delete');

Open the todo url in the browser. Now you can perform edit and delete operation in this todo app.

You can download full source code from this link.

Leave a Reply

Your email address will not be published. Required fields are marked *