Simple product crud in laravel-8 with simple pagination
NOTE: Before start make sure php, composer, nodejs, npm and mysql must be installed on your system.
To create a new laravel project by using composer, open the terminal where you want to create project:
composer create-project --prefer-dist laravel/laravel:^8.0 crud
After the installation complete then , go into the project folder;
cd crud
Let’s make a product crud in laravel 8, so first thing first we have to make a migration for product:
php artisan make:migration create_products_table
Note:
1- The syntax to create migration, you must type the ‘create’ at the first and ‘table’ at the last and in the middle ‘table name’ with the ‘_’ concatenation.
2- The table name must be plural.
Now make columns in the table (products) we have just created.
database/migrations/2021_05_17_131915_create_products_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->longText('description')->nullable();
$table->string('color')->nullable();
$table->bigInteger('price')->nullable();
$table->bigInteger('weight')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Now, create a model of products, model is used to handle the business logic's, So,
php artisan make:model Product
The product model look like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'description',
'color',
'price',
'weight',
];
}
Now, create a controller to process HTTP requests and return back the result to the web browser and also to communicate with the models and views.
php artisan make:controller ProductController -r# -r means resource, used to make the resource controller
Let’s write the code for product crud in this controller,
app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::simplePaginate(2);
return view('index', compact('products', $products));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$product = Product::create([
'name' => $request->name,
'color' => $request->color,
'weight' => $request->weight,
'price' => $request->price,
'description' => $request->description,
]);
return redirect()->back()->with('success', 'Product successfully stored.');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$product = Product::findOrFail($id);
return view('show', compact('product', $product));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$product = Product::findOrFail($id);
return view('edit', compact('product', $product));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$product = Product::findOrFail($id);
$product->update([
'name' => $request->name,
'color' => $request->color,
'weight' => $request->weight,
'price' => $request->price,
'description' => $request->description,
]);
return redirect()->back()->with('success', 'Product successfully updated.');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$product = Product::findOrFail($id);
$product->delete();
return redirect()->back()->with('success', 'Product successfully deleted.');
}
}
Now, create the following blade file as mention below:
resources/views/layouts/master.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Product Crud</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
</head>
<body>
<div class="row justify-content-center mt-5">
<div class="col-6">
@yield('content')
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
</body>
</html>
resources/views/create.blade.php
@extends('layouts.master')
@section('content')
<div class="d-flex justify-content-between mb-4">
<h3>Create Product</h3>
<a class="btn btn-success btn-sm" href="{{ route('index') }}">List Products</a>
</div>
@if(session()->has('success'))
<label class="alert alert-success w-100">{{session('success')}}</label>
@elseif(session()->has('error'))
<label class="alert alert-danger w-100">{{session('error')}}</label>
@endif
<form action="{{ route('store') }}" method="POST">
@csrf
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="product name">
</div>
<div class="form-group">
<label>Color</label>
<input type="color" name="color" class="form-control" placeholder="product color">
</div>
<div class="row">
<div class="col-12">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Weight</label>
<input type="text" name="weight" class="form-control" placeholder="product weight">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" placeholder="product price">
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea name="description" rows="5" placeholder="product description" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@endsection
resources/views/edit.blade.php
@extends('layouts.master')
@section('content')
<div class="d-flex justify-content-between mb-4">
<h3>Edit Product</h3>
<a class="btn btn-success btn-sm" href="{{ route('index') }}">List Products</a>
</div>
@if(session()->has('success'))
<label class="alert alert-success w-100">{{session('success')}}</label>
@elseif(session()->has('error'))
<label class="alert alert-danger w-100">{{session('error')}}</label>
@endif
<form action="{{ route('update', ['id' => $product->id]) }}" method="POST">
@csrf
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="product name" value="{{ $product->name }}">
</div>
<div class="form-group">
<label>Color</label>
<input type="color" name="color" class="form-control" placeholder="product color" value="{{ $product->color }}">
</div>
<div class="row">
<div class="col-12">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Weight</label>
<input type="text" name="weight" class="form-control" placeholder="product weight" value="{{ $product->weight }}">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" placeholder="product price" value="{{ $product->price }}">
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea name="description" rows="5" placeholder="product description" class="form-control">{{ $product->description }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@endsection
resources/views/index.blade.php
@extends('layouts.master')
@section('content')
<div class="d-flex justify-content-between mb-4">
<h3>Products List</h3>
<a class="btn btn-success btn-sm" href="{{ route('create') }}">Create New</a>
</div>
@if(session()->has('success'))
<label class="alert alert-success w-100">{{session('success')}}</label>
@elseif(session()->has('error'))
<label class="alert alert-danger w-100">{{session('error')}}</label>
@endif
<table class="table table-striped">
<thead>
<tr>
<th>Created At</th>
<th>Name</th>
<th>Weight</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach($products as $product)
<tr>
<td>{{ $product->created_at }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->weight }}</td>
<td>{{ $product->price }}</td>
<td>
<a href="{{ route('edit', ['id' => $product->id]) }}" class="btn btn-success btn-sm">Edit</a>
<a href="{{ route('show', ['id' => $product->id]) }}" class="btn btn-info btn-sm">Show</a>
<form action="{{ route('delete', ['id' => $product->id]) }}" method="POST" class="d-inline-block">
@csrf
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="d-flex justify-content-between">
{{ $products->render() }}
</div>
@endsection
resources/views/show.blade.php
@extends('layouts.master')
@section('content')
<div class="d-flex justify-content-between mb-4">
<h3>Show Product</h3>
<a class="btn btn-success btn-sm" href="{{ route('index') }}">List Products</a>
</div>
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="{{ $product->name }}" disabled>
</div>
<div class="form-group">
<label>Color</label>
<input type="color" name="color" class="form-control" value="{{ $product->color }}" disabled>
</div>
<div class="form-group">
<label>Weight</label>
<input type="text" name="weight" class="form-control" value="{{ $product->weight }}" disabled>
</div>
<div class="form-group">
<label>Description</label>
<textarea name="description" rows="5" placeholder="product description" class="form-control" disabled>{{ $product->description }}</textarea>
</div>
@endsection
Now, write the routes in the web.php file:
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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::get('/', [\App\Http\Controllers\ProductController::class, 'index'])->name('index');
Route::get('/create', [\App\Http\Controllers\ProductController::class, 'create'])->name('create');
Route::get('/show/{id}', [\App\Http\Controllers\ProductController::class, 'show'])->name('show');
Route::get('/edit/{id}', [\App\Http\Controllers\ProductController::class, 'edit'])->name('edit');
Route::post('/update/{id}', [\App\Http\Controllers\ProductController::class, 'update'])->name('update');
Route::post('/store', [\App\Http\Controllers\ProductController::class, 'store'])->name('store');
Route::post('/delete/{id}', [\App\Http\Controllers\ProductController::class, 'destroy'])->name('delete');
Add the database credentials in the .env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel # your database name
DB_USERNAME=root #your database username
DB_PASSWORD=password #your database password
The final step is to run the migration:
php artisan migrate
Now, run the project and test:
php artisan serve
I hope it helps!