FahmidasClassroom

Learn by easy steps

Laravel7crud

Laravel 7 is released on 3rd March 2020. Many new features are added in this new version, such as, improved routing cache speed, improved blade components, laravel airlock etc. How you can implement CRUD using Laravel is shown in this tutorial.

Steps:

1. First of all you have to install a fresh copy of laravel 7. Go to the folder where you want create Laravel project and open command prompt. Run the following command to create a new Laravel 7 project.

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

2. Go to the project folder and run the following command to check the installed version of the laravel.

php artisan --version

3. Run the project from xampp server

http://localhost/laravel-crud/public

4. Create a database named laravel and open .env file to set the database connection.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=''

5. Run the following command create a migration file to create a customer table.

 php artisan make:migration create_customers_table --create=customers

6. Open the migration file from database/migration folder and modify the code with the following code.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCustomersTable extends Migration
{
/**
* Run the migrations.
* * @return void
*/

	public function up()
	{
		Schema::create('customers', function (Blueprint $table) {
		$table->id();
		$table->string('name');
		$table->string('email');
		$table->string('address');
		$table->timestamps();
	});
	}

/**
* Reverse the migrations.
*
* @return void
*/

	public function down()
	{
		Schema::dropIfExists('customers');
	}

}

7. The following migrate command to create the table.

 php artisan migrate

8. Run the following command to create customer resource controller.

 php artisan make:controller CustomerController --resource

9. Run the following command to create customer model.

 php artisan make:model Customer

10. Modify model Customer.php with the following code.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
	protected $fillable = ['name', 'email','address'];
}

11. Open CustomerController from app/Http/Cotrollers folder. Modify the code with the following code.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Customer;
use Redirect,Response;
class CustomerController extends Controller
{

	/**
	* Display a listing of the resource.
	*
	* @return \Illuminate\Http\Response
	*/

	public function index()
	{
		$customers = Customer::latest()->paginate(4);
		return view('customers.index',compact('customers'))->with('i', (request()->input('page', 1) - 1) * 4);
	}

	/**
	* Show the form for creating a new resource.
	*
	* @return \Illuminate\Http\Response
	*/

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

	/**
	* Store a newly created resource in storage.
	*
	* @param \Illuminate\Http\Request $request
	* @return \Illuminate\Http\Response
	*/

	public function store(Request $request)
	{

		$r=$request->validate([
		'name' => 'required',
		'email' => 'required',
		'address' => 'required',
		]);

		$custId = $request->cust_id;
		Customer::updateOrCreate(['id' => $custId],['name' => $request->name, 'email' => $request->email,'address'=>$request->address]);
		if(empty($request->cust_id))
			$msg = 'Customer entry created successfully.';
		else
			$msg = 'Customer data is updated successfully';
		return redirect()->route('customers.index')->with('success',$msg);
	}

	/**
	* Display the specified resource.
	*
	* @param int $id
	* @return \Illuminate\Http\Response
	*/

	public function show(Customer $customer)
	{
		return view('customers.show',compact('customer'));
	}

	/**
	* Show the form for editing the specified resource.
	*
	* @param int $id
	* @return \Illuminate\Http\Response
	*/
	
	public function edit($id)
	{
		$where = array('id' => $id);
		$customer = Customer::where($where)->first();
		return Response::json($customer);
	}

	/**
	* Update the specified resource in storage.
	*
	* @param \Illuminate\Http\Request $request
	* @param int $id
	* @return \Illuminate\Http\Response
	*/

	public function update(Request $request)
	{

	}

	/**
	* Remove the specified resource from storage.
	*
	* @param int $id
	* @return \Illuminate\Http\Response
	*/

	public function destroy($id)
	{
		$cust = Customer::where('id',$id)->delete();
		return Response::json($cust);
	}
}

12. Open web.php from routes folder and add the following code at the end of the file.

 Route::resource('customers','CustomerController');
 Route::get('customers/{id}/edit/','CustomerController@edit');

13. Create two blade files named index.blade.php and layout.blade.php under the resources/views/customers/ folder.
14.  Add the following code to layout.blade.php.

<!DOCTYPE html>

<html>
<head>
<title>Laravel7 CRUD @fahmidasclassroom.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
<script>
$(document).ready(function () {

/* When click New customer button */
$('#new-customer').click(function () {
$('#btn-save').val("create-customer");
$('#customer').trigger("reset");
$('#customerCrudModal').html("Add New Customer");
$('#crud-modal').modal('show');
});

/* Edit customer */
$('body').on('click', '#edit-customer', function () {
var customer_id = $(this).data('id');
$.get('customers/'+customer_id+'/edit', function (data) {
$('#customerCrudModal').html("Edit customer");
$('#btn-update').val("Update");
$('#btn-save').prop('disabled',false);
$('#crud-modal').modal('show');
$('#cust_id').val(data.id);
$('#name').val(data.name);
$('#email').val(data.email);
$('#address').val(data.address);
})
});
/* Show customer */
$('body').on('click', '#show-customer', function () {
$('#customerCrudModal-show').html("Customer Details");
$('#crud-modal-show').modal('show');
});

/* Delete customer */
$('body').on('click', '#delete-customer', function () {
var customer_id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
confirm("Are You sure want to delete !");

$.ajax({
type: "DELETE",
url: "http://localhost/laravel7crud/public/customers/"+customer_id,
data: {
"id": customer_id,
"_token": token,
},
success: function (data) {
$('#msg').html('Customer entry deleted successfully');
$("#customer_id_" + customer_id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});

</script>
</html>

15.  Add the following code to index.blade.php.

@extends('customers.layout')
@section('content')
<div class="row">
<div class="col-lg-12" style="text-align: center">
<div >
<h2>Laravel 7 CRUD using Bootstrap Modal</h2>
</div>
<br/>
</div>
</div>
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-right">
<a href="javascript:void(0)" class="btn btn-success mb-2" id="new-customer" data-toggle="modal">New Customer</a>
</div>
</div>
</div>
<br/>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p id="msg">{{ $message }}</p>
</div>
@endif
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th width="280px">Action</th>
</tr>

@foreach ($customers as $customer)
<tr id="customer_id_{{ $customer->id }}">
<td>{{ $customer->id }}</td>
<td>{{ $customer->name }}</td>
<td>{{ $customer->email }}</td>
<td>{{ $customer->address }}</td>
<td>
<form action="{{ route('customers.destroy',$customer->id) }}" method="POST">
<a class="btn btn-info" id="show-customer" data-toggle="modal" data-id="{{ $customer->id }}" >Show</a>
<a href="javascript:void(0)" class="btn btn-success" id="edit-customer" data-toggle="modal" data-id="{{ $customer->id }}">Edit </a>
<meta name="csrf-token" content="{{ csrf_token() }}">
<a id="delete-customer" data-id="{{ $customer->id }}" class="btn btn-danger delete-user">Delete</a></td>
</form>
</td>
</tr>
@endforeach

</table>
{!! $customers->links() !!}
<!-- Add and Edit customer modal -->
<div class="modal fade" id="crud-modal" aria-hidden="true" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="customerCrudModal"></h4>
</div>
<div class="modal-body">
<form name="custForm" action="{{ route('customers.store') }}" method="POST">
<input type="hidden" name="cust_id" id="cust_id" >
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" id="name" class="form-control" placeholder="Name" onchange="validate()" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Email:</strong>
<input type="text" name="email" id="email" class="form-control" placeholder="Email" onchange="validate()">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Address:</strong>
<input type="text" name="address" id="address" class="form-control" placeholder="Address" onchange="validate()" onkeypress="validate()">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" id="btn-save" name="btnsave" class="btn btn-primary" disabled>Submit</button>
<a href="{{ route('customers.index') }}" class="btn btn-danger">Cancel</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Show customer modal -->
<div class="modal fade" id="crud-modal-show" aria-hidden="true" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="customerCrudModal-show"></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-2 col-sm-2 col-md-2"></div>
<div class="col-xs-10 col-sm-10 col-md-10 ">
@if(isset($customer->name))

<table>
<tr><td><strong>Name:</strong></td><td>{{$customer->name}}</td></tr>
<tr><td><strong>Email:</strong></td><td>{{$customer->email}}</td></tr>
<tr><td><strong>Address:</strong></td><td>{{$customer->address}}</td></tr>
<tr><td colspan="2" style="text-align: right "><a href="{{ route('customers.index') }}" class="btn btn-danger">OK</a> </td></tr>
</table>
@endif
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
<script>
error=false

function validate()
{
	if(document.custForm.name.value !='' && document.custForm.email.value !='' && document.custForm.address.value !='')
	    document.custForm.btnsave.disabled=false
	else
		document.custForm.btnsave.disabled=true
}
</script>

16.  Now, Laravel crud project is ready to run.

The steps are shown in the following video.