Hello, today I want to talk about the CRUD in Laravel. In programming, to write scalable, reusable, and clean code, you need to follow some programming principles.
What is CRUD?
CRUD refers to the four basic operations a software application should be able to perform: create, read, update, and delete.
STEP 1: Installing Laravel via Composer
You can ignore this step if you already have an application downloaded, or else run the following command to create a brand new Laravel project.
composer create-project laravel/laravel {directory} 10.0 --prefer-dist
STEP 2: Configure Database Connection
In this type of project, we must give precedence to the database connection; generally, it should be configured before getting started. Incorporate the following code in the. env file with your database details.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
STEP 3: Building Your First Model
Today we are going to create a blog post. Because of that, we need to have posts in our database. So now we can create a model called ‘Post’ by following the below command.
php artisan make:model Post -m
Note: -m means migration. When we use -m with the model make command
Each migration is stored in the database/migrations directory. And each migration filename contains a timestamp that allows Laravel to determine the order of the migrations.
2024_02_08_071146_create_posts_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('content');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
STEP 4: Run Migrations in Laravel
Laravel Migration is a developer-friendly feature in Laravel that allows you to create a table in your database. It allows you to modify and share the application's database schema. You can modify the table by adding a new column or deleting an existing column.
It’s time to migrate the model into the database. To do this, run the below command in your terminal or cmd.
php artisan migrate
After running this command, you will be able to see some new tables added under your database.
STEP 5: Creating Your First Controller
A controller is the C in the MVC model-view-controller, and Laravel is an MVC framework. The controller is where you enter or code most of your application logic.
php artisan make:controller PostController
All the controllers are located under the app/http/controllers route in Laravel. If you navigate to the above route, you can see our newly created controller.
STEP 6: Create Form For Save Database
First, we need to create a form to submit data to the database. I am using Bootstrap because of its simplicity for UI and view. and we need to create a form to insert data into the database.
//create-page.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Blog Post Application</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous">
</script>
</head>
<body>
<div class="container mt-5">
<form method="POST" action="{{route(post.store)}}">
@csrf
<div class="form-group mb-2">
<label for="name"></label>
<input type="text" class="form-control" name="title" placeholder="Enter blog title">
</div>
<div class="form-group mb-2">
<label for="content">Content</label>
<textarea id="content" name="content" rows="4" cols="50"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
STEP 7: Create all routes.
We use the POST method to send the data from the frontend to the backend, and I also use ‘post.store’ as my router to make this post request. We will create this later.
Keep in mind to add @csrf inside the form tag.
Now we are going to create all the routes for this CRUD application. Open your web.php file and edit it like below.
<?php
//routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
*/
Route::group(['prefix' => 'post','as'=>'post.'], function () {
Route::get('/', [PostController::class, 'index'])->name('index');
Route::get('/create', [PostController::class, 'create'])->name('create');
Route::post('/store', [PostController::class, 'store'])->name('store');
Route::get('/edit/{id}', [PostController::class, 'edit'])->name('edit');
Route::put('/update/{id}', [PostController::class, 'update'])->name('update');
Route::delete('/delete/{id}', [PostController::class, 'delete'])->name('delete');
});
STEP 8: Create a post controller.
Then we can create all our CRUD operations inside our controller.
<?php
//App/Http/Controllers/PostController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
public function index(){
$posts = Post::all();
return view('index-post',compact('posts'));
}
public function create(){
return view('create-post');
}
public function store(Request $request){
//validate data before insert to database
$validator= Validator::make($request->all(),[
'title'=>'required|min:5',
'content'=>'required'
]);
$post = new Post();
$post->title = $request->title;
$post->content = $request->content;
$post->saev();
return redirect()->back();
}
public function edit(Request $request,$id){
$post = Post::find($id);
return view('edit-post',compact('post'));
}
public function update(Request $request,$id){
//validate data before update to database
$validator= Validator::make($request->all(),[
'title'=>'required|min:5',
'content'=>'required'
]);
$post = Post::find($id);
$post->title = $request->title;
$post->content = $request->content;
$post->saev();
return redirect()->back();
}
public function delete(Request $request,$id){
$post = Post::find($id);
$post->delete();
return redirect()->back();
}
}
STEP 9: Create a table for the data presented.
Then we need to have a table to display data under the table. To do that, add the below code inside the view at the //index-page.blade.php file.
//index-page.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Blog Post Application</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</head>
<body>
<div class="container mt-5">
<table class="table mt-5">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Title</th>
<th scope="col">Content</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach ($posts as $key => $data)
<tr>
<th>{{ $key + 1 }}</th>
<th>{{ $data->title }}</th>
<th>{{ $data->content }}</th>
<th>
<a href="{{route('post.edit',$data->id)}}" class="btn btn-primary">Edit</a>
<a href="javascript:;" class="btn btn-danger" onclick="if(confirm('Are you sure you want to delete this row ?')) { event.preventDefault();document.getElementById('delete-form{{$data->id}}').submit();}"><i class="flaticon2-trash"></i></a>
<form id="delete-form{{$data->id}}" action="{{route('post.delete',[$data->id])}}" method="POST" class="d-none">
@csrf
{{method_field('DELETE')}}
</form>
</th>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>
</html>
STEP 10: Create a create an update form.
we need to create an update form to update data to the database.
//update-page.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Blog Post Application</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous">
</script>
</head>
<body>
<div class="container mt-5">
<form method="POST" action="{{route('post.update',$post->id)}}">
@csrf
{{ method_field('PUT') }}
<div class="form-group mb-2">
<label for="name"></label>
<input type="text" class="form-control" name="title" placeholder="Enter blog title" value="{{$post->title}}">
</div>
<div class="form-group mb-2">
<label for="content">Content</label>
<textarea id="content" name="content" rows="4" cols="50">value="{{$post->content}}"</textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>