Laravel 6 CRUD application will contain the approach to create and use the Insert, Select, Update, and Delete functionalities. You can build your own advanced applications by using this concept in Laravel 6. Laravel has several inbuilt features that make it more secure, robust, and authentic to our application. Before moving to the Laravel 6 crud tutorial, make sure your system is ready for creating Laravel applications. If you haven’t configured your system for Laravel then please go through the Installation of Laravel 6 in Windows and Ubuntu
Requirements for Creating Laravel 6 Project
It is most important, follows the below requirements before creating a new project.
- PHP >= 7.2.0 version.
- OpenSSL extension for the PHP.
- BCMath PHP Extension.
- Ctype PHP Extension
- JSON PHP Extension
- Mbstring PHP Extension
- PDO PHP Extension
- Tokenizer PHP Extension
- XML PHP Extension
Prerequisites
For creating this Laravel 6 CRUD application, I’m going to use the Visual Studio Code. However, if you haven’t downloaded then please download and configure it for the development. You can use any editor as you want.
Consequently, let’s continue to the project.
How to Upload Files and Images in Laravel 6 with Validation
Create New Laravel 6 CRUD Project
To create a new project in Laravel 6, we’ll be using the composer-create project command. Just open your command prompt (windows user) and type the below command.
composer create-project --prefer-dist laravel/laravel crud
It will create a folder with the application name and will start the installation of the Laravel.
Once the project creation has been completed, navigate to the project directory by the cd
command.
Laravel 6 Login and Registration with Authentication
Install Frontend Dependencies in Laravel
Laravel provides the front-end dependencies so you will need to install it by the following command.
npm install
Create and Configure MySQL Database
- Open phpMyAdmin and create a new database there. In my case, I have created a database with a name
laravel6_crud
- Now, in the project folder navigate to .env file and configure the MySQL database credentials as below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6_crud
DB_USERNAME=root
DB_PASSWORD=root
Actually, I am going to create the laravel 6 crud application in which, I will work on the student module. Here, I will store the student’s data into the database table. Then, that data will be retrieved in a tabular format. Also, I will work for edit/update and delete of the student record.
Dropdown Selection Filter in PHP Using jQuery Ajax
Create the Model and Migration Files
In the next step, create a Model with the migration of the table. Laravel provides a way to create the database table using command. Using the migration the laravel can manage the version of the database table on each update of fields.
For creating the Model, laravel has artisan command. So, type the below command to create the model and also a migration file. Here, I am going to create a Model of Student along with it’s migration file.
php artisan make:model Student --migration
Once, the migration file has been created navigate to the database->migrations in your project files.
Now, open the create_students_table.php file inside the migrations. Set the students table schema as below.
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('full_name');
$table->date('dob');
$table->string('gender');
$table->string('email');
$table->string('phone');
$table->string('address');
$table->integer('zipcode');
$table->tinyInteger('is_deleted')->default(0);
$table->timestamps();
});
}
Ajax PHP Form Handling Using jQuery – Submit Form Without Refresh
Add Fillable Data in Model
Open the Student model inside the app and paste the below code for mass assignment in the students table.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
// Mass Assignment
protected $fillable = [
'first_name', 'last_name', 'full_name', 'dob', 'gender', 'address', 'zipcode'
];
}
Migrate the Database Table
Once, you have done with the model, it’s time to migrate the table schema into the database. During migration, the schema of the table will be created into the database. The migration contains the version of the table schema which can be managed anytime.
php artisan migrate
Here, in the migration, the laravel has created the tables in the database automatically for which the migration has been created.
So you can see here, the migration table has been created successfully.
You can check into the database for the tables that have been created after the migration.
Check Email Available in PHP MySQL Using jQuery and Ajax
Create Controller in Laravel 6
For our laravel 6 crud operation, we will need to create a controller for the student in which we’ll handle the logical operations of the students.
Therefore to create the controller you will need to type the below artisan command in the terminal.
php artisan make:controller StudentController --resource
The above command will create a StudentController with the resource. Laravel provides the resource as the list of methods for performing the CRUD operations.
The list of resource methods are the following-
- index()
- create()
- store()
- show()
- edit()
- update()
- destroy()
Hence, we can use the above methods for CRUD operations. You can custom methods too. But for that, you will have to define the routes.
Create Routes in Laravel 6
Routing in the laravel is the most important part which defines the interface of the web URL of the controller. In other words, when the method calls, these routes load. On the other hand, it is the only way which helps us to manage the request URL in the laravel.
Therefore, creating the routes of the StudentController, navigate to the routes folder and open the web.php file.
In this post, we are creating the Web Application so our routes will be defined under the web.php file. Similarly, when we’ll work on the REST API then we’ll need to define the routes under the api.php file.
You can see the route list in the laravel by the following command –
php artisan route:list
It will display all the routes available in the controller. In our case, we have the StudentController with the resource methods. So, here all the routes are listed with the name, action and the middleware.
Methods | URI | Name | Action | Middleware
=======================================================================================================================
GET|HEAD | student | student.index | App\Http\Controllers\StudentController@index | web |
POST | student | student.store | App\Http\Controllers\StudentController@store | web |
GET|HEAD | student/create | student.create | App\Http\Controllers\StudentController@create | web |
GET|HEAD | student/{student} | student.show | App\Http\Controllers\StudentController@show | web |
PUT|PATCH | student/{student} | student.update | App\Http\Controllers\StudentController@update | web |
DELETE | student/{student} | student.destroy | App\Http\Controllers\StudentController@destroy | web |
GET|HEAD | student/{student}/edit | student.edit | App\Http\Controllers\StudentController@edit | web |
Route::resource('student', 'StudentController');
How to Implement jQuery Datatable in PHP with MySQL
Create Views in Laravel 6
In the next step, we will require to create views for the student. Views mainly define the user interface from which you can interact with. All the design interfaces contain by the views.
All the views reside under the resources->views folder. In the laravel, views can be created with the .blade.php extension.
So, I’ll be creating the following views here-
- layout.blade.php
- create.blade.php
- index.blade.php
- show.blade.php
- update.blade.php
The layout.blade.php file is the master layout and I will use this blade file in the other blade file by extending it.
{{-- layout.blade.php --}}
<!DOCTYPE html>
<html lang="en">
<head>
<title> Laravel 6 CRUD Example </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
@yield('content')
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Next, I will extend the above layout for creating the form. So, for create.blade.php file, paste the below code.
{{ -- create.blade.php -- }}
@extends('./student/head')
<body>
<div class="container mt-3">
<form action="{{ route('student.store') }}" method="post">
<div class="row">
<div class="col-xl-8 p-4 m-auto shadow">
<div class="card">
<div class="card-header">
<h5 class="card-title text-info"> Add Student </h5>
</div>
<div class="card-body">
{{-- print success message --}}
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<div class="form-group" {{ $errors->has('first_name') ? 'has-error' : ''}}>
<label> First Name </label>
<input type="text" name="first_name" placeholder="First Name" class="form-control" value="{{ old('first_name')}}">
{!! $errors->first('first_name', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group" {{ $errors->has('dob') ? 'has-error' : ''}}>
<label> Date of Birth </label>
<input type="date" name="dob" placeholder="Date of Birth" class="form-control" value="{{ old('dob') }}">
{!! $errors->first('dob', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group" {{ $errors->has('email') ? 'has-error' : ''}}>
<label> Email </label>
<input type="text" name="email" placeholder="Email" class="form-control" value="{{ old('email') }}">
{!! $errors->first('email', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group" {{ $errors->has('address') ? 'has-error' : ''}}>
<label> Address </label>
<input class="form-control" placeholder="Address" type="text" name="address" value="{{ old('address') }}">
{!! $errors->first('address', '<small class="text-danger">:message </small>') !!}
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<div class="form-group" {{ $errors->has('last_name') ? 'has-error' : ''}}>
<label> Last Name </label>
<input type="text" name="last_name" placeholder="Last Name" class="form-control" value="{{ old('last_name') }}">
{!! $errors->first('last_name', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group" {{ $errors->has('gender') ? 'has-error' : ''}}>
<label> Gender </label>
<select class="form-control" name="gender" value="{{ old('gender') }}">
<option disabled selected> Select Gender </option>
<option value="male"> Male </option>
<option value="female"> Female </option>
</select>
{!! $errors->first('gender', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group" {{ $errors->has('phone') ? 'has-error' : ''}}>
<label> Phone </label>
<input type="phone" name="phone" placeholder="Phone no" class="form-control" value="{{ old('phone') }}">
{!! $errors->first('phone', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group" {{ $errors->has('zipcode') ? 'has-error' : ''}}>
<label> Zipcode </label>
<input type="number" name="zipcode" class="form-control" placeholder="Zipcode" value="{{ old('zipcode') }}">
{!! $errors->first('zipcode', '<small class="text-danger">:message </small>') !!}
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" name="submit"> Submit </button>
</div>
{{csrf_field()}}
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
@include('/student/footer')
In the above blade file, I have added form action to the store() method of the StudentController. Also, I have added the validation errors to next of each form fields. But, for this, you’ll have to add the validation rules in the controller in the same method.
If the data will be inserted, it will display a success message with the session. Once, you are done with above, it is time to load the blade into the controller’s method.
Load Blade File into Controller
Once, you have created the blade files, it required to load the blade.php files in the controller’s method. As we know that, we can run blade file (views) directly in the MVC. So navigate to the StudentController.php file and inside the create() method just paste the below code to load the create.blade.php file.
public function create()
{
return view('student/create');
}
Run Laravel Project
To see the result we need to run the laravel project by artisan command.
php artisan serve
The laravel default host will be started on localhost with port 8000. So according to the route we can access the student controller by the following URL.
http://localhost:8000/student/create
It will show the result like this.
Add Form Validation Rules and Save Data
In this step, we will add validation rules for the form so that the controller will return to the form if form fields are null. The form action of create.blade.php file to the store() method of StudentController. So, we’ll need to add the validation rules inside the store() method.
Also, after the validation success, the data will be inserted into the database.
public function store(Request $request) {
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'gender' => 'required',
'dob' => 'required',
'email' => 'required|email',
'phone' => 'required',
'address' => 'required',
'zipcode' => 'required',
]);
$input = $request->all();
$input['full_name'] = $input['first_name'] . " ".$input['last_name'];
$student = Student::create($input);
return back()->with('success', 'Record created successfully');
}
In the below result, you can see the validation errors are properly displayed after each input field.
If the inputs are validated, the data will insert into the database.
So, I have added some data into the database.
Now, I will fetch all the data from the student table.
Listing Data in Laravel 6 CRUD Example
For displaying all the data from the database, you will require to write the below code inside the index() function of the StudentController.
public function index()
{
// Display data
$students = Student::all();
// passing data into view
return view('student/index', compact('students'));
}
Now, you will need to create a table inside the index.blade.php file which has created above.
@extends('./student/layout')
<div class="container mt-5">
<div class="row">
<div class="col-md-12">
<a href="{{ url('student/create') }}" class="btn btn-info float-right"><i class="fas fa-plus-circle"></i> Add New </a>
</div>
</div>
<table class="table table-striped table-bordered mt-4">
<thead>
<th> Name </th>
<th> DOB </th>
<th> Gender </th>
<th> Email </th>
<th> Phone </th>
<th> Address </th>
<th> Zipcode </th>
<th> Action </th>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<td> {{ $student->full_name }} </td>
<td> {{ $student->dob }} </td>
<td> {{ $student->gender }} </td>
<td> {{ $student->email }} </td>
<td> {{ $student->phone }} </td>
<td> {{ $student->address }} </td>
<td> {{ $student->zipcode }} </td>
<td> <a href="{{ route('student.show', $student->id )}}" class="badge badge-info"> View </a>
<a href="{{ route('student.edit', $student->id )}}" class="badge badge-success"> Edit </a>
<form action="{{ route('student.destroy', $student->id)}}" method="post">
@csrf
@method('DELETE')
<button class="badge btn-danger" type="submit"> Delete </button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
Display Single Data in Laravel 6 CRUD
In the table of student listing, I have defined the action as View, Edit and Delete. So, when you will click on the View option, it will redirect you to another blade file in which the selected student record will be displayed there.
public function show($id)
{
$student = Student::find($id);
return view('student/show', compact('student'));
}
Now, paste the below snippet in the show.blade.php file.
{{ show.blade.php }}
@extends('student/layout')
<div class="container mt-3">
<div class="row">
<div class="col-xl-8 p-4 m-auto shadow">
<div class="card">
<div class="card-header">
<h5 class="card-title text-info"> Show Student </h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<div class="form-group">
<label> First Name </label>
<input type="text" name="first_name" disabled placeholder="First Name" class="form-control" value="{{ $student->first_name}}">
</div>
<div class="form-group">
<label> Date of Birth </label>
<input type="date" name="dob" disabled placeholder="Date of Birth" class="form-control" value="{{ $student->dob }}">
</div>
<div class="form-group">
<label> Email </label>
<input type="text" name="email" disabled placeholder="Email" class="form-control" value="{{ $student->email }}">
</div>
<div class="form-group">
<label> Address </label>
<input class="form-control" disabled placeholder="Address" type="text" name="address" value="{{ $student->address }}">
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<div class="form-group">
<label> Last Name </label>
<input type="text" name="last_name" disabled placeholder="Last Name" class="form-control" value="{{ $student->last_name }}">
</div>
<div class="form-group">
<label> Gender </label>
<select class="form-control" name="gender" disabled>
@if($student->gender == "male")
<option value="male" selected> Male </option>
@elseif($student->gender == "female")
<option value="female"> Female </option>
@endif
</select>
</div>
<div class="form-group">
<label> Phone </label>
<input type="phone" name="phone" disabled placeholder="Phone no" class="form-control" value="{{ $student->phone }}">
</div>
<div class="form-group">
<label> Zipcode </label>
<input type="number" name="zipcode" disabled class="form-control" placeholder="Zipcode" value="{{ $student->zipcode}}">
</div>
</div>
</div>
<div class="form-group">
<a href=" {{ route('student.index')}}" class="btn btn-danger"> Close <i class="fa fa-times-circle"></i></a>
</div>
</div>
</div>
</div>
</div>
When you will click on the View button, then on the basis of the id of the selected student, all the data will be loaded into a form with disabled inputs.
Edit and Update Data in Laravel 6
In the next step, I will edit and update the student data on the basis of the id. So when you will click on the edit button, it will redirect you to the update.blade.php file with all the data.
public function edit($id)
{
$student = Student::find($id);
return view('student/update', compact('student'));
}
Then paste the below code, in the update.blade.php file.
@extends('./student/layout')
<body>
<div class="container mt-3">
<form action="{{ route('student.update', $student->id) }}" method="post">
{{csrf_field() }}
@method('PATCH')
<div class="row">
<div class="col-xl-8 p-4 m-auto shadow">
<div class="card">
<div class="card-header">
<h5 class="card-title text-info"> Update Student </h5>
</div>
<div class="card-body">
{{-- print success message --}}
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<div class="form-group" {{ $errors->has('first_name') ? 'has-error' : ''}}>
<label> First Name </label>
<input type="text" name="first_name" placeholder="First Name" class="form-control" value="{{ $student->first_name }}">
{!! $errors->first('first_name', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group" {{ $errors->has('dob') ? 'has-error' : ''}}>
<label> Date of Birth </label>
<input type="date" name="dob" placeholder="Date of Birth" class="form-control" value="{{ $student->dob }}">
{!! $errors->first('dob', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group" {{ $errors->has('email') ? 'has-error' : ''}}>
<label> Email </label>
<input type="text" name="email" placeholder="Email" class="form-control" value="{{ $student->email }}">
{!! $errors->first('email', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group" {{ $errors->has('address') ? 'has-error' : ''}}>
<label> Address </label>
<input class="form-control" placeholder="Address" type="text" name="address" value="{{ $student->address }}">
{!! $errors->first('address', '<small class="text-danger">:message </small>') !!}
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<div class="form-group" {{ $errors->has('last_name') ? 'has-error' : ''}}>
<label> Last Name </label>
<input type="text" name="last_name" placeholder="Last Name" class="form-control" value="{{ $student->last_name }}">
{!! $errors->first('last_name', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group" {{ $errors->has('gender') ? 'has-error' : ''}}>
<label> Gender </label>
<select class="form-control text-capitalize" name="gender" value="{{ old('gender') }}">
<option value="{{ $student->gender }}"> {{ $student->gender }} </option>
@if($student->gender == "male")
<option value="female"> Female </option>
@else
<option value="male"> Male </option>
@endif
</select>
{!! $errors->first('gender', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group" {{ $errors->has('phone') ? 'has-error' : ''}}>
<label> Phone </label>
<input type="phone" name="phone" placeholder="Phone no" class="form-control" value="{{ $student->phone }}">
{!! $errors->first('phone', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group" {{ $errors->has('zipcode') ? 'has-error' : ''}}>
<label> Zipcode </label>
<input type="number" name="zipcode" class="form-control" placeholder="Zipcode" value="{{ $student->zipcode }}">
{!! $errors->first('zipcode', '<small class="text-danger">:message </small>') !!}
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" name="submit"> Submit </button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Update Data By Id
Here, I’m going to update the student detail by student id. So, after clicking the update button the form action will go to the update method inside the StudentController. Paste the below snippet there.
// update student
public function update(Request $request, $id)
{
$student = $request->validate([
'first_name' => 'required',
'last_name' => 'required',
'gender' => 'required',
'dob' => 'required',
'email' => 'required|email',
'phone' => 'required',
'address' => 'required',
'zipcode' => 'required',
]);
$student['full_name'] = $student['first_name'] . " ".$student['last_name'];
Student::where('id', $id)->update($student);
return back()->with('success', 'Record updated successfully');
}
Here is the result after updating the record.
Delete Student Record in Laravel 6 CRUD
In this step, the delete operation will be performed by the student id.
// delete student
public function destroy($id)
{
$student = Student::findOrFail($id);
$student->delete();
return redirect('student')->with('success', 'Student deleted successfully');
}
Conclusion
In this Laravel CRUD tutorial, I have tried to show you a very simple approach to work with the data in the Laravel 6 with MySQL database using Laravel 6 CRUD Example. Here, in this tutorial, I have shown you the step by step guide to create, read, update and delete the data using the Laravel 6 eloquent. I hope this will help you to implement the real projects in Laravel.
Shainy Varghese says
Sir my update is not working. When i submit for updating the data no changes is happening.
kindly help me to solve this issue.
Umesh Rana says
Hey Shainy,
Make sure you are passing the correct parameters like the id (primary field) and the data value which will gonna update. If you are getting any error then please show me the error message, so that I can see what is the actual problem.
Shainy Varghese says
yes sir, i had made mistake in that. Now the whole code is working perfect.
Thank You so much sir.
Raice says
Hi there
I Did check well where are the controller file and functions?
Umesh Rana says
I elaborated all the functions one by one separately. After creating the resource controller, we have the resource methods. So, just start from this link-
https://programmingfields.com/laravel-6-crud-application/#Add_Form_Validation_Rules_and_Save_Data