Laravel 6 CRUD Operation

Whenever you learn any framework then Insert, Update and Delete it basic operation to learn any new framework. In this lesson, I will explain you how to create basic CRUD application in Laravel 6.

This tutorial covers the use of Routes, Controller, Blade files, Models and Migration for CRUD operation.

Laravel 6 Basic Server Requirements

  • PHP >= 7.2.0
  • BCMath PHP Extension
  • Ctype PHP Extension
  • Fileinfo PHP extension
  • JSON PHP Extension
  • Mbstring PHP Extension
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension

Laravel 6 Installation

Before start with installation of Laravel, we assume you have already setup of composer in your system.

Now, please open command prompt OR terminal and run below command:

composer create-project --prefer-dist laravel/laravel blog

Database Configuration (MySql)

Please open .env file and do configuration for database connection:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6_crud
DB_USERNAME=root
DB_PASSWORD=

Create Migration

Here, we are going to create CRUD operation for Tasks. So, first, we create migration for Tasks table using Artisan command. Please run below code in command line:

php artisan make:migration create_tasks_table

When you run this commend then it will create new file to “database/migrations” directory. Now, open this file and write below code for database schema:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tasks');
}
}

Now, run following migration command to create table in database:

php artisan migrate

Add Route

Now, open ‘routes/web.php’ and define the following route:

routes:web.php
Route::resource('tasks','TaskController');

By writing this line, you are registering the following multiple routes:

Add Controller and Model

Now, create the TaskController with model. For this, run the following command:

php artisan make:controller TaskController --resource --model=Task

When you run this command then it will create two files in the following path:

app/Http/Controllers/TaskController.php
app/Task.php

When you open “TaskController.php” file then you can see predefined methods as below:

  • index()
  • create()
  • store()
  • show()
  • edit()
  • update()
  • destroy()

Create Views

Now, create views at “resources >> views” directory. First, create the following views files under “resources >> views >> tasks” directory.

  1. index.blade.php
  2. create.blade.php
  3. edit.blade.php

Now, create “layout.blabe.php” file under “resources >> views” directory.

<!DOCTYPE html>
<html>
<head>
<title>Laravel 6 CRUD Operation</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>

<div class="container">
@yield('content')
</div>

</body>
</html>

This is the main template file and we will extend other view files with this main template.

Now, start with create code and for this, write the following code in “create.blade.php” under “resources >> views >> tasks” directory.

@extends('layout')

@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Add New Task</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('tasks.index') }}"> Back</a>
</div>
</div>
</div>

@if ($errors->any())
<div class="alert alert-danger">
There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<form action="{{ route('tasks.store') }}" method="POST">
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Title:</strong>
<input type="text" name="title" class="form-control" placeholder="Please Enter Title">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Description:</strong>
<textarea class="form-control" name="description" placeholder="Please Enter Description"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center"><button type="submit" class="btn btn-primary">Submit</button></div>
</div>

</form>
@endsection

Now, open “TaskController.php” and write the following code for “create()” method:

public function create()
{
return view('tasks.create');
}

Now, run following command and open “http://127.0.0.1:8000/tasks/create” OR “http://localhost:8000/tasks/create” URL:

php artisan serve

Now, we will write code for submit create form. 

For this, we will use “store()” method. Write below code to store() method:

public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);

Task::create($request->all());

return redirect()->route('tasks.index')->with('success','Task created successfully.');
}

Here, you can see some validation rules before store the data. You can also define your own validation rules using Laravel Validation.

If you form will not validate then it will show errors as below:

Now, if you fill all fields with value then it will create new record to the database.

Display Data

Now, we will write the code in index() method to view list of tasks.

public function index()
{
$tasks = Task::all();

return view('tasks.index',compact('tasks'));
}

Now, write the following code in “index.blade.php” file

@extends('layout')

@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>List of Tasks</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('tasks.create') }}"> Create New Task</a>
</div>
</div>
</div>

@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif

<table class="table table-bordered">
<tr>
<th>Title</th>
<th>Description</th>
<th colspan="2">Action</th>
</tr>
@foreach ($tasks as $task)
<tr>
<td>{{ $task->title }}</td>
<td>{{ $task->description }}</td>
<td><a class="btn btn-primary" href="{{ route('tasks.edit',$task->id) }}">Edit</a></td>
<td>
<form action="{{ route('tasks.destroy',$task->id) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
@endsection

Edit Operation

Now, write below code in “edit()” method for edit form:

public function edit(Task $task)
{
return view('tasks.edit',compact('task'));
}

After that, add the following code to “edit.blade.php” file:

@extends('layout')

@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Task</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('tasks.index') }}"> Back</a>
</div>
</div>
</div>

@if ($errors->any())
<div class="alert alert-danger">
There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<form action="{{ route('tasks.update',$task->id) }}" method="POST">
@csrf
@method('PUT')

<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Title:</strong>
<input type="text" name="title" value="{{ $task->title }}" class="form-control" placeholder="Please Enter Title">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Description:</strong>
<textarea class="form-control" name="description" placeholder="Please Enter Description">{{ $task->description }}</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>

</form>
@endsection

Now, we will write the following code in TaskController.php for update the data in “update()” method

public function update(Request $request, Task $task)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);

$task->update($request->all());

return redirect()->route('tasks.index')->with('success','Task updated successfully');
}

Here, we are doing same validation as we did in “create()” method to store data.

Delete Operation

Write the following code in “destroy()” method in to delete the record.

public function destroy(Task $task)
{
$task->delete();

return redirect()->route('tasks.index')->with('success','Task deleted successfully');
}

Please  click here for Github code.