Laravel 8 CRUD(create, read, update, delete) application.
In this tutorial, you learn how to perform crud in laravel. In this project we use laravel 8 and bootstrap cdn . For the simplicity i don’t install npm or any webmix.
We can find this project on GitHub click here.
We will complete our project by performing the below steps-
- Install Laravel Project using composer.
- Config database setting.
- Make Model and Migration
- Make a Controller and write down all necessary functions(index, create, store, edit, update, show, delete).
- Define all possible routes.
- Create all view files (index, create, edit, show).
Before Starting Project make sure you have installed composer, or you can download it from this link — download composer.
For checking composer to cmd or git bash and run the below command-
composer -V
Step:1
Install a fresh new laravel project by running the below command, also you can check laravel doc.
composer create-project laravel/laravel:^8.0 example-app
After running this command wait for a few seconds.
Step:2
Open your project to VS-CODE or your favorite code editor, then go to .env
file and set your database name, in my case it is laravel_crud
After that start xampp and create a new database as per your .env
database name.
Now time to run migration by running the below command.
php artisan migrate
Done, you successfully migrate your database. Now time to go next step.
Step:3
Perform the below command to create a model and corresponding migration. you can check laravel eloquent for more details. We are creating a Blog model. Model name should be camelcase.
php artisan make:model Blog -m
By performing this command new model and a corresponding migration are created. Model location is app->Models->Blog.php and migration location is app->database->migrations.
Now We add some code to the Blog
Model.
protected $fillable = ['title','details','status'];
Now we add all necessary columns in the migration file, in my case, I take only 3 columns title, details, and status.
public function up(){Schema::create('blogs', function (Blueprint $table) {$table->id();$table->text('title');$table->longText('details');$table->string('status')->default('Active');$table->timestamps();});}
After that run php artisan migrate
yeah, the blog table is created successfully in your database. check phpMyAdmin.
Step:4
php aritsan make:controller BlogController
Run this command for creating a new Controller, in my case controller name is BlogController
. Controller located in app->Http->Controllers
Now We write all possible functions for building a crud application.
READ
Read All data from the database by the below function, in this function we read all the data from the database and return a view file with all data. (we create all view files after these steps don’t worry), just follow me.
/*** Show All blogs*/public function index(){$blogs = Blog::all();return view('blogs.index',['blogs' => $blogs]);}
CREATE
In this method, we return just a form for creating a new blog.
/*** show a form for creating new blog*/public function create(){return view('blogs.create');}
STORE
By the store method, save all the $request
data to the database. In this method first, we validate all the data, and after that, we save all data and return back with a SESSION
.
/*** store a blog into database*/public function store(Request $request){$request->validate(['title' => 'required','details' => 'required','status' => 'required']);Blog::create(['title' => $request->title,'details' => $request->details,'status' => $request->status,]);return back()->with('blog_create_success','Blog Created Successfully');}
EDIT
Show a form for editing an existing single blog. that's why we return a view file with a blog
data.
/*** show a edit form for updating blog*/public function edit($id){$blog = Blog::findOrFail($id);return view('blogs.edit',['blog' => $blog]);}
UPDATE
In this method, we update a specific blog. First, we validate the data and update this and return back with a session.
/*** update a blog*/public function update(Request $request,$id){$request->validate(['title' => 'required','details' => 'required','status' => 'required']);Blog::where('id',$id)->update(['title' => $request->title,'details' => $request->details,'status' => $request->status,]);return back()->with('blog_update_success','Blog Updated Successfully');}
SHOW
Using the show method we view a single blog with all information.
/*** show a blog*/public function show($id){$blog = Blog::findOrFail($id);return view('blogs.show',['blog' => $blog]);}
DELETE
In this method, we delete a single blog
/*** destroy a blog*/public function destroy($id){$blog = Blog::findOrFail($id);$blog->delete();return back()->with('blog_delete_success','Blog Deleted Successfully');}
Setps:5
Define all possible routes to the web.php
file. web.php
file located to routes->web.php
Route::get('/',[BlogController::class,'index'])->name('blog.index');Route::get('/blog/create',[BlogController::class,'create'])->name('blog.create');Route::post('/blog/store',[BlogController::class,'store'])->name('blog.store');Route::get('/blog/edit/{id}',[BlogController::class,'edit'])->name('blog.edit');Route::post('/blog/update/{id}',[BlogController::class,'update'])->name('blog.update');Route::get('/blog/show/{id}',[BlogController::class,'show'])->name('blog.show');Route::get('/blog/delete/{id}',[BlogController::class,'destroy'])->name('blog.delete');
Setps:6
Now time to create all view files.
Create blogs directory inside the view folder. resources->views->blogs.
index.blade.php
<!DOCTYPE html><html lang="{{ str_replace('_', '-', app()->getLocale()) }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Laravel CRUD</title><!-- Fonts --><link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"><!-- Styles --><style>body {font-family: 'Nunito';}</style></head><body class="antialiased"><div class="container mt-4"><div class="row"><div class="col-12"><div class="card"><div class="card-header"><div class="card-title">All Blogs</div><a href="{{ route('blog.create') }}" class="btn btn-primary btn-sm text-end">Create Blog</a></div><div class="card-body">@if (Session::has('blog_create_success'))<div class="alert alert-success">{{ Session::get('blog_create_success') }}</div>@endif@if (Session::has('blog_delete_success'))<div class="alert alert-danger">{{ Session::get('blog_delete_success') }}</div>@endif<table class="table table-striped"><thead><tr><th>Serial</th><th>Title</th><th>Status</th><th>Actions</th></tr></thead><tbody>@forelse ($blogs as $blog)<tr><td>{{ $loop->iteration }}</td><td>{{ $blog->title }}</td><td><span class="badge {{ $blog->status == 'Active'?'bg-success':'bg-danger' }}">{{ $blog->status }}</span></td><td><a href="{{route('blog.show',$blog->id) }}" class="btn btn-sm btn-primary">Show</a><a href="{{ route('blog.edit',$blog->id) }}" class="btn btn-sm btn-info">Edit</a><a href="{{ route('blog.delete',$blog->id) }}" class="btn btn-sm btn-danger">Delete</a></td></tr>@empty<tr><td colspan="4" class="text-center">No Blog Found</td></tr>@endforelse</tbody></table></div></div></div></div></div></body><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script></html>
create.blade.php
<!DOCTYPE html><html lang="{{ str_replace('_', '-', app()->getLocale()) }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Laravel CRUD</title><!-- Fonts --><link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"><!-- Styles --><style>body {font-family: 'Nunito';}</style></head><body class="antialiased"><div class="container mt-4"><div class="row"><div class="col-12"><div class="card"><div class="card-header"><div class="card-title">Create New Blog</div><a href="{{ route('blog.index') }}" class="btn btn-primary btn-sm text-end">All Blog</a></div><div class="card-body">@if (Session::has('blog_create_success'))<div class="alert alert-success">{{ Session::get('blog_create_success') }}</div>@endif<form action="{{ route('blog.store') }}" method="POST">@csrf<div class="form-group mb-2"><label>Title <span class="text-danger">*</span></label><input type="text" class="form-control" name="title">@error('title')<div class="text-danger">{{ $message }}</div>@enderror</div><div class="form-group mb-2"><label>Details <span class="text-danger">*</span></label><input type="text" class="form-control" name="details">@error('details')<div class="text-danger">{{ $message }}</div>@enderror</div><div class="form-group mb-2"><label>Status <span class="text-danger">*</span></label><select class="form-select" name="status"><option value="">select status</option><option value="Active">Active</option><option value="Deactive">Deactive</option></select>@error('status')<div class="text-danger">{{ $message }}</div>@enderror</div><button type="submit" class="btn btn-sm btn-primary">Submit</button></form></div></div></div></div></div></body><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script></html>
edit.blade.php
<!DOCTYPE html><html lang="{{ str_replace('_', '-', app()->getLocale()) }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Laravel CRUD</title><!-- Fonts --><link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"><!-- Styles --><style>body {font-family: 'Nunito';}</style></head><body class="antialiased"><div class="container mt-4"><div class="row"><div class="col-12"><div class="card"><div class="card-header"><div class="card-title">Edit Blog</div><a href="{{ route('blog.index') }}" class="btn btn-primary btn-sm text-end">All Blog</a></div><div class="card-body">@if (Session::has('blog_create_success'))<div class="alert alert-success">{{ Session::get('blog_create_success') }}</div>@endif<form action="{{ route('blog.update',$blog->id) }}" method="POST">@csrf<div class="form-group mb-2"><label>Title <span class="text-danger">*</span></label><input type="text" class="form-control" name="title" value="{{ $blog->title }}">@error('title')<div class="text-danger">{{ $message }}</div>@enderror</div><div class="form-group mb-2"><label>Details <span class="text-danger">*</span></label><input type="text" class="form-control" name="details" value="{{ $blog->details }}">@error('details')<div class="text-danger">{{ $message }}</div>@enderror</div><div class="form-group mb-2"><label>Status <span class="text-danger">*</span></label><select class="form-select" name="status"><option value="">select status</option><option {{ $blog->status == 'Active'?'selected':'' }} value="Active">Active</option><option {{ $blog->status == 'Deactive'?'selected':'' }} value="Deactive">Deactive</option></select>@error('status')<div class="text-danger">{{ $message }}</div>@enderror</div><button type="submit" class="btn btn-sm btn-primary">Update</button></form></div></div></div></div></div></body><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script></html>
show.blade.php
<!DOCTYPE html><html lang="{{ str_replace('_', '-', app()->getLocale()) }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Laravel CRUD</title><!-- Fonts --><link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"><style>body {font-family: 'Nunito';}</style></head><body class="antialiased"><div class="container mt-4"><div class="row"><div class="col-12"><div class="card"><div class="card-header"><div class="card-title">Show Blog</div><a href="{{ route('blog.index') }}" class="btn btn-primary btn-sm text-end">All Blog</a></div><div class="card-body"><h3>Title</h3><p>{{ $blog->title }}</p><hr><h3>Details</h3><p>{{ $blog->details }}</p><hr><h3>Status</h3><p>{{ $blog->status }}</p><hr></div></div></div></div></div></div></body><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script></html>
Done, Now time to serve the application
php artisan serve
Run this command. after that it will serve at http://127.0.0.1:8000/ in my case
Thanks for reading this article. Have a good day.