How Can I Create CRUD Example From Scratch In Laravel

admin_img Posted By Bajarangi soft , Posted On 25-09-2020

In Laravel for each project we can insert ,update, delete and show the data so today we are going to create crud (Create Read Update Delete) Application in laravel you will understand how to use resource route, controller, blade files, model and migration for crud operation in laravel

How Can I Create CRUD Example From Scratch In Laravel

Step 1:Create new project using below command 

composer create-project --prefer-dist laravel/laravel blog

Step 2:Create route in web.php file as below created.
Route::resource('products','ProductController');

Step 3:Create model,controller and migration files using below command
php artisan make:model Product -mcr


Step 4:Open Product model file,Product controller file ,Product migration files and implement code as below in files 

database/migrations/2020_09_25_060902_create_products_table.php
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('product_name');
            $table->text('description');
            $table->text('image');
            $table->date('date');
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

after creating migration file run below command
php artisan migrate

app/Product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'product_name', 'description','image','date'
    ];
}


 app/Http/controller/ProductController.php
<?php

namespace App\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::latest()->paginate(5);

        return view('products.index',compact('products'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    public function create()
    {
        return view('products.create');
    }


    public function store(Request $request)
    {

        $input=$request->all();
        $this->validate($request, [
            'product_name' => 'required',
            'description' => 'required',
            'image' => 'required|nullable|image|mimes:jpeg,png,jpg,gif,svg|max:1999',
        ]);
        $input=$request->except('image');
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $name = time().'.'.$image->getClientOriginalExtension();
            $destinationPath = public_path('/images');
            $image->move($destinationPath, $name);
            $input['image']=$name;
        }

        Product::create($input);

        return redirect()->route('products.index')
            ->with('success','Product created successfully.');
    }


    public function show(Product $product)
    {
        return view('products.show',compact('product'));
    }

    public function edit(Product $product)
    {
        return view('products.edit',compact('product'));
    }

    public function update(Request $request, Product $product)
    {
        $input=$request->all();
        $this->validate($request, [
            'product_name' => 'required',
            'description' => 'required',
        ]);
        $input=$request->except('image');
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $name = time().'.'.$image->getClientOriginalExtension();
            $destinationPath = public_path('/images');
            $image->move($destinationPath, $name);
            $input['image']=$name;
        }


        $product->update($input);

        return redirect()->route('products.index')
            ->with('success','Product updated successfully');
    }

    public function destroy(Product $product)
    {
        $product->delete();

        return redirect()->route('products.index')
            ->with('success','Product deleted successfully');
    }
}


Step 5:Create blade files to save data and retrieve data from controller 
First create product folder in that create below blade.files
Index.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="align-content-center">
                    <h2>Laravel CRUD</h2>
                </div>
            </div>
        </div>

            @if ($message = Session::get('success'))
                <div class="alert alert-success">
                    <p>{{ $message }}</p>
                </div>
            @endif

        <table class="table table-bordered">
            <tr>
                <th>No</th>
                <th>Product Name</th>
                <th>Description</th>
                <th>Image</th>
                <th>Date</th>
                <th><a class="btn btn-success " href="{{ route('products.create') }}"> Add New Product</a></th>
            </tr>
                    @foreach ($products as $product)
                        <tr>
                            <td>{{ ++$i }}</td>
                            <td>{{ $product->product_name }}</td>
                            <td>{{ $product->description }}</td>
                            <td style="width:16%"><img src="{{asset('images/'.$product->image)  }}" alt="image" style="width: 50%;"></td>
                            <td>{{ $product->date }}</td>
                            <td>
                                <form action="{{ route('products.destroy',$product->id) }}" method="POST" >

                                    <a class="btn btn-secondary" href="{{ route('products.show',$product->id) }}">Show</a>

                                    <a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>

                                    @csrf
                                    @method('DELETE')

                                    <button type="submit" class="btn btn-danger">Delete</button>
                                </form>
                            </td>
                        </tr>
                    @endforeach
        </table>

            {!! $products->links() !!}
    </div>

@endsection

Create.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-lg-12 ">
                <div class="text-center">
                    <h2>Add New Product</h2>
                </div>
            </div>
        </div>

        @if ($errors->any())
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">
            @csrf

            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Product Name:</strong>
                        <input type="text" name="product_name" class="form-control" placeholder="Name">
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Description:</strong>
                        <textarea class="form-control" style="height:150px" name="description" placeholder="Description"></textarea>
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Image:</strong>
                        <input type="file" name="image"  >
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">

                    <div class="form-group">
                        <strong>Date</strong>
                        <input type="text" name="date" class="form-control" placeholder="Date">
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12 ">
                    <button type="submit" class="btn btn-success">Submit</button>
                    <a class="btn btn-default" href="{{ route('products.index') }}"> Back</a>
                </div>
            </div>

        </form>
    </div>

@endsection

edit.blade.php

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="text-center">
                    <h2>Edit Product</h2>
                </div>

            </div>
        </div>

        @if ($errors->any())
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('products.update',$product->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Name:</strong>
                        <input type="text" name="product_name" value="{{ $product->product_name }}" class="form-control" placeholder="Name">
                    </div>
                </div>



                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Description:</strong>
                        <textarea class="form-control" style="height:150px" name="description" placeholder="Description">{{ $product->description }}</textarea>
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Image:</strong>
                        <input type="file" name="image" value="{{ $product->image }}" >
                    </div>
                    {{ $product->image }}
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Date</strong>
                        <input type="text" name="date" class="form-control" value="{{ $product->date }}">
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12 ">
                    <button type="submit" class="btn btn-primary">Update</button>
                    <a class="btn btn-default" href="{{ route('products.index') }}"> Back</a>
                </div>
            </div>

        </form>
    </div>
@endsection

show.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="text-center">
                    <h2> Details of Product</h2>
                </div>
            </div>
        </div>

        <div class="row">

            <div class="col-xs-12 col-sm-12 col-md-12">

                <div class="form-group">

                    <h1>Product Name:</h1>

                    <h3>{{ $product->product_name }}</h3>
                </div>
            </div>

            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <h1>Description:</h1>
                   <h3> {{ $product->description }}</h3>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <h1>Image:</h1>
                    <img src="{{asset('images/'.$product->image)  }}" alt="image" style="width: 50%;">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <h1>Date:</h1>
                    <h3> {{ $product->date }}</h3>
                </div>
            </div>
            <a class="btn btn-default" href="{{ route('products.index') }}"> Back</a>
        </div>
    </div>
@endsection


Step 6:Now pass below URL  in google chrome
http://localhost/laraveldemoproject/public/products

Related Post