Life of a developer begins with CRUD, in a computer programming word this word is a fundamental building block of almost every mobile and web application.
CRUD stands for creating, read, update, delete, these four basic methods establish the consensus with the database. CRUD operations mean creating, reading, updating and deleting a record while interacting with a database.
In this Laravel tutorial, you will learn from beginning how to create a Laravel CRUD project with MySQL database.
Throughout this tutorial, you will develop the basic idea of working with Laravel PHP Framework with MySQL database.
Laravel is a PHP based free, open-source PHP web framework, developed by Taylor Otwell exclusively for web applications development.
It follows the model–view–controller architectural pattern and based on Symfony, not only but also a superior web app development framework; it comes with an expressive, elegant syntax.
Install Laravel Application
You must have composer set up on your development machine, open console enter the command and press enter to create a new Laravel app:
composer create-project laravel/laravel --prefer-dist laravel-crud-example
Add Database Details in ENV
Put the database name, username and password in .env configuration file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=
Organize Model and Migration
Now, you have to create a model; it will create a database table with some properties:
php artisan make:model Employee -m
Add the table values in migration file inside the database/migrations/create_employees_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('phone');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
}
Define the table values in $fillable
array within the app/Models/Employee.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $fillable = [
'name',
'email',
'phone'
];
}
Eventually, run the migration:
php artisan migrate
Create Controller
Now, create a new controller with below common:
A resource controller is mainly used for manifesting a controller that holds almost every http request that needs to be made through the laravel application.
php artisan make:controller EmployeeController --resource
Put the below code in app/Http/Controllers/EmployeeController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$employee = Employee::all();
return view('index', compact('employee'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('welcome');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$storeData = $request->validate([
'name' => 'required|max:255',
'email' => 'required|max:255',
'phone' => 'required|numeric',
]);
$employee = Employee::create($storeData);
return redirect('/employees')->with('completed', 'Employee created!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$employee = Employee::findOrFail($id);
return view('update', compact('employee'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$data = $request->validate([
'name' => 'required|max:255',
'email' => 'required|max:255',
'phone' => 'required|numeric',
]);
Employee::whereId($id)->update($data);
return redirect('/employees')->with('completed', 'Employee updated');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$employee = Employee::findOrFail($id);
$employee->delete();
return redirect('/employees')->with('completed', 'Employee deleted');
}
}
Create Routes
Routes enable navigation as well as API calls, so put the below code in routes/web.php:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::resource('employees', EmployeeController::class);
Using below command shows you the routes on your console screen:
php artisan route:list
+--------+-----------+---------------------------+-------------------+-------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+-----------+---------------------------+-------------------+-------------------------------------------------+------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | api/user | | Closure | api |
| | | | | | auth:api |
| | GET|HEAD | employees | employees.index | App\Http\Controllers\EmployeeController@index | web |
| | POST | employees | employees.store | App\Http\Controllers\EmployeeController@store | web |
| | GET|HEAD | employees/create | employees.create | App\Http\Controllers\EmployeeController@create | web |
| | GET|HEAD | employees/{employee} | employees.show | App\Http\Controllers\EmployeeController@show | web |
| | PUT|PATCH | employees/{employee} | employees.update | App\Http\Controllers\EmployeeController@update | web |
| | DELETE | employees/{employee} | employees.destroy | App\Http\Controllers\EmployeeController@destroy | web |
| | GET|HEAD | employees/{employee}/edit | employees.edit | App\Http\Controllers\EmployeeController@edit | web |
+--------+-----------+---------------------------+-------------------+-------------------------------------------------+---------
Create Blade Partial Views
Partial views are great for managing templates, you will define the master view, additionally see how to pass the variable to the partial layout view.
Create the following files within resources/views:
- index.blade.php
- layout.blade.php
- update.blade.php
- welcome.blade.php
Set Up Master Layout
The master partial displays the CRUD application’s primary view, place the Bootstrap CSS link in the head area and display the master layout to define the primary content variable.
Place the below code in main layout.blade.php
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Laravel 8 CRUD Operations Example</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
@yield('content')
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" type="text/js"></script>
</body>
</html>
We have to create a form to create, store and validate a user data using Bootstrap Form and Card UI components.
Add the following code in the resources/views/welcome.blade.php file.
@extends('layout')
@section('content')
<div class="card mt-5">
<div class="card-header">
Create User
</div>
<div class="card-body">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form method="post" action="{{ route('employees.store') }}">
<div class="form-group">
@csrf
<label for="name">Name</label>
<input type="text" class="form-control" name="name"/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email"/>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="tel" class="form-control" name="phone"/>
</div>
<button type="submit" class="btn btn-block btn-primary">Add</button>
</form>
</div>
</div>
@endsection
Put the given below code in resources/views/index.blade.php to display the employees data in table:
@extends('layout')
@section('content')
<div class="mt-5">
@if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
@endif
<table class="table">
<thead>
<tr class="table-primary">
<td># ID</td>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Action</td>
</tr>
</thead>
<tbody>
@foreach($employee as $employee)
<tr>
<td>{{$employee->id}}</td>
<td>{{$employee->name}}</td>
<td>{{$employee->email}}</td>
<td>{{$employee->phone}}</td>
<td class="text-center">
<a href="{{ route('employees.edit', $employee->id)}}" class="btn btn-success btn-sm">Edit</a>
<form action="{{ route('employees.destroy', $employee->id)}}" method="post" style="display: inline-block">
@csrf
@method('DELETE')
<button class="btn btn-danger btn-sm" type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
<div>
@endsection
Put code code in resources/views/update.blade.php file:
@extends('layout')
@section('content')
<div class="card mt-5">
<div class="card-header">
Update
</div>
<div class="card-body">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form method="post" action="{{ route('employees.update', $employee->id) }}">
<div class="form-group">
@csrf
@method('PATCH')
<label for="name">Name</label>
<input type="text" class="form-control" name="name" value="{{ $employee->name }}" />
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" value="{{ $employee->email }}" />
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="tel" class="form-control" name="phone" value="{{ $employee->phone }}" />
</div>
<button type="submit" class="btn btn-block btn-danger">Update</button>
</form>
</div>
</div>
@endsection
Run command to start the project:
php artisan serve
http://127.0.0.1:8000/employees
Laravel CRUD Operations tutorial is over, i hope it will be helpful to you:
Download Code: GitHub