Hello Dev’s
Today in this tutorial i am going to discuss on laravel 8 crud operation example. Now in this tutorial i will create a simple crud operation app on laravel 8 from scratch. If you are new to laravel then I hope you are on right place. I will discuss laravel 8 crud from scratch for beginner.
You know that laravel 8 was released few months ago. On this update laravel change lots of things. That’s why i will show you Laravel 8 CRUD operations tutorial. We will learn from here how to fetch data by using get request, how delete data by using delete request, how to edit or update data by using put or patch request and also show how to save or insert data by using post request.
Now in this laravel 8 crud tutorial i will create a product model and i will generate crud using this product model. Today in this laravel 8 crud tutorial i also use route model binding to see single data or update to hiding the id of customer and also i will use product slug rather id to show single data. So you just have to follow some few steps and you will get basic crud stuff by using controller, model, route, bootstrap 4 and blade.
So I will also validate the form before submit and also i will show error message of form request data. It is going to be a very short and simple crud operation of Laravel 8 application for beginners. CRUD is a very common operation for every application. So let’s learn laravel crud operation from scratch for beginner.
List table of Contents
- Setup Laravel 8 project
- Connect with Database
- Make Model and Migration
- Create Routes
- Make Controller
- Make Blade File
- Conclusion
Step -1 : Setup Laravel 8 project
First we need to installing composer,If you have not install composer then click here to download and install composer. After ready our environment just run below command to download a fresh laravel application. We are now going to start Laravel 8 crud from steps by steps. So let’s download it by using bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Connect DatabaseÂ
After download new laravel 8 application. Now in this step we need to connect database on our project. Because without database we can’t insert update view or delete our data on our application. So let’s connect it as like as below.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE= db_name
DB_USERNAME=root
DB_PASSWORD=
Step 3: Make Model and Migration
That’s good,now in this step we have to create a new model and migration to get table in laravel 8 crud application. So let’s run below command to create a new model and migration file.
php artisan make:model Product-m
Read Also :
database/migrations/create_products_table.php
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->string('details');
$table->timestamps();
});
}
Now we need to run this below command to migrate your new table.
php artisan migrate
Now open product model and paste the below code in this file.
app/Product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
// protected $guarded = []; or you can use
protected $fillable = [
'name',
'slug',
'details'
];
public function getRouteKeyName()
{
return 'slug';
}
}
Step 4 : Create Routes
Now on this time to create our new routes to make laravel crud applications. Now please open “routes/web.php” and paste below code here.
routes/web.php
Route::get('/product', 'TestController@add_product_form')->name('product.add');
Route::post('/product', 'TestController@submit_product_data')->name('product.save');
Route::get('/product/list', 'TestController@fetch_all_product')->name('product.list');
Route::get('/product/edit/{product}', 'TestController@edit_product_form')->name('product.edit');
Route::patch('/product/edit/{customer}', 'TestController@edit_product_form_submit')->name('product.update');
Route::get('/product/{product}', 'TestController@view_single_product')->name('product.view');
Route::delete('/product/{product}', 'TestController@delete_product')->name('product.delete');
Step 5:Â Create Controller
In this step we need to create our TestController to create all the method to complete laravel crud operation. So run below command to create TestController
php artisan make:controller TestController
Now in this step open TestController and paste this below code in it.
app/Http/Controllers/TestController.php
namespace App\Http\Controllers;
use App\Customer;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function add_product_form()
{
if( \View::exists('product.create') ){
return view('product.create');
}
}
public function submit_product_data(Request $request)
{
$rules = [
'name' => 'required|min:6',
'slug' => 'required|unique:product'
];
$errorMessage = [
'required' => 'Enter your :attribute first.'
];
$this->validate($request, $rules, $errorMessage);
Product::create([
'name' => $request->name,
'slug' => \Str::slug($request->slug),
'details' => strtolower($request->details)
]);
$this->meesage('message','product created successfully!');
return redirect()->back();
}
public function fetch_all_product()
{
$products= Product::toBase()->get();
return view('product.index',compact('products'));
}
public function edit_product_form(Product $product)
{
return view('product.edit',compact('product'));
}
public function edit_product_form_submit(Request $request, Product $product)
{
$rules = [
'name' => 'required|min:6',
];
$errorMessage = [
'required' => 'Enter your :attribute first.'
];
$this->validate($request, $rules, $errorMessage);
$customer->update([
'name' => $request->name,
]);
$this->meesage('message','Product updated successfully!');
return redirect()->back();
}
public function view_single_product(Product $product)
{
return view('product.view',compact('product'));
}
public function delete_product(Product $product)
{
$customer->delete();
$this->meesage('message','Product deleted successfully!');
return redirect()->back();
}
public function meesage(string $name = null, string $message = null)
{
return session()->flash($name,$message);
}
}
Step 6: Create Blade File
Now we are in our final step to complete this laravel 8 crud tutorial example. Now Just we need to create some new blade file to see our data and form to submit new data.Â
resources/views/layouts/app.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">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<script src="{{ asset('js/app.js') }}" defer></script>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
@stack('style')
</head>
<body>
<div id="app">
<nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
<div class="container">
<a class="navbar-brand" href="{{ url('/') }}">
{{ config('app.name', 'Laravel') }}
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"></ul>
<ul class="navbar-nav ml-auto">
@guest
<li class="nav-item">
<a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
</li>
@if (Route::has('register'))
<li class="nav-item">
<a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
</li>
@endif
@else
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
@csrf
</form>
</div>
</li>
@endguest
</ul>
</div>
</div>
</nav>
<main class="py-4">
@yield('content')
</main>
</div>
</body>
</html>
resources/views/product/create.blade.php
@extends('layouts.app')
@push('style')
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
@endpush
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
@if(session()->has('message'))
<p class="btn btn-success btn-block btn-sm custom_message text-left">{{ session()->get('message') }}</p>
@endif
<legend style="color: green; font-weight: bold;">LARAVEL 8 CRUD EXAMPLE - codingspoint
<a href="{{ route('product.list') }}" style="float: right; display: block;color: white; background-color: green; padding: 1px 5px 1px 5px; text-decoration: none; border-radius: 5px; font-size: 17px;"> CUSTOMER LIST</a>
</legend>
<form action="{{ route('product.save') }}" method="post">
@csrf
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Enter name">
<font style="color:red"> {{ $errors->has('name') ? $errors->first('name') : '' }} </font>
</div>
<div class="form-group">
<label for="">Details</label>
<input type="text" class="form-control" name="details" value="{{ old('email') }}" placeholder="Enter email">
<font style="color:red"> {{ $errors->has('details') ? $errors->first('email') : '' }} </font>
</div>
<div class="form-group" style="margin-top: 24px;">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</form>
</div>
</div>
</div>
@endsection
Read Also : PHP Laravel File Upload with Progress Bar Example
resources/views/customer/edit.blade.php Â
@extends('layouts.app')
@push('style')
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
@endpush
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
@if(session()->has('message'))
<p class="btn btn-success btn-block btn-sm custom_message text-left">{{ session()->get('message') }}</p>
@endif
<legend style="color: green; font-weight: bold;">LARAVEL 8 CRUD EXAMPLE - CODINGSPOINT
<a href="{{ route('product.list') }}" style="float: right; display: block;color: white; background-color: green; padding: 1px 5px 1px 5px; text-decoration: none; border-radius: 5px; font-size: 17px;"> CUSTOMER LIST</a>
</legend>
<form action="{{ route('product.update',$product->slug) }}" method="post">
@csrf
@method('patch')
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="name" value="{{ $customer->name}}">
<font style="color:red"> {{ $errors->has('name') ? $errors->first('name') : '' }} </font>
</div>
<div class="form-group">
<label for="">Details</label>
<input type="text" class="form-control" name="details" value="{{ $customer->email }}">
<font style="color:red"> {{ $errors->has('details') ? $errors->first('email') : '' }} </font>
</div>
<div class="form-group" style="margin-top: 24px;">
<input type="submit" class="btn btn-success" value="Update">
</div>
</form>
</div>
</div>
</div>
@endsection
resources/views/customer/index.blade.php
@extends('layouts.app')
@push('style')
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
@endpush
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
@if(session()->has('message'))
<p class="btn btn-success btn-block btn-sm custom_message text-left">{{ session()->get('message') }}</p>
@endif
<legend style="color: green; font-weight: bold;">LARAVEL 8 CRUD EXAMPLE - CODINGSPOINT
<a href="{{ route('product.add') }}" style="float: right; display: block;color: white; background-color: green; padding: 1px 5px 1px 5px; text-decoration: none; border-radius: 5px; font-size: 17px;"> ADD CUSTOMER</a>
</legend>
<table id="example1" class="table table-bordered table-hover">
<thead>
<tr class="text-center">
<th class="text-center">No</th>
<th class="text-center">Name</th>
<th class="text-center">Details</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
@forelse ($products as $product)
<tr class="text-center">
<td class="text-center">{{ $loop->index + 1 }}</td>
<td class="text-center">{{ $product->name }}</td>
<td class="text-center">{{ $product->detail}}</td>
<td class="text-center">
<a href="{{ route('product.edit',$product->slug) }}" class="btn btn-sm btn-outline-danger py-0">Edit</a>
<a href="{{ route('product.view',$product->slug) }}" class="btn btn-sm btn-outline-danger py-0">View</a>
<a href="" onclick="if(confirm('Do you want to delete this product?'))event.preventDefault(); document.getElementById('delete-{{$product->slug}}').submit();" class="btn btn-sm btn-outline-danger py-0">Delete</a>
<form id="delete-{{$product->slug}}" method="post" action="{{route('product.delete',$product->slug)}}" style="display: none;">
@csrf
@method('DELETE')
</form>
</td>
</tr>
@empty
<p> No product found!</p>
@endforelse
</tbody>
</table>
</div>
</div>
</div>
@endsection
resources/views/customer/view.blade.php
@extends('layouts.app')
@push('style')
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
@endpush
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<legend style="color: green; font-weight: bold;">LARAVEL 7.X CRUD EXAMPLE - CODINGSPOINT
<a href="{{ route('product.list') }}" style="float: right; display: block;color: white; background-color: green; padding: 1px 5px 1px 5px; text-decoration: none; border-radius: 5px; font-size: 17px;"> CUSTOMER LIST</a>
</legend>
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="name" value="{{ $customer->name}}">
<font style="color:red"> {{ $errors->has('name') ? $errors->first('name') : '' }} </font>
</div>
<div class="form-group">
<label for="">Details</label>
<input type="text" class="form-control" name="details" value="{{ $customer->email }}">
<font style="color:red"> {{ $errors->has('details') ? $errors->first('email') : '' }} </font>
</div>
<div class="form-group" style="margin-top: 24px;">
<a href="{{ route('product.list') }}" class="btn btn-success">Back</a>
</div>
</div>
</div>
</div>
@endsection
Read Also : Ajax CRUD with Laravel 8 Tutorial with Example for Beginners
Now our laravel 8 crud example tutorial is done. Now we can check it by visiting the following url.
URL
http://localhost:8000/product
thanks for reading. I hope it will help you,