Laravel 6 CRUD Example Tutorial (Step By Step)

Laravel 6 CRUD Example Tutorial (Step By Step)

Laravel 6 create a CRUD(create, read, update, delete) application using MySQL database tutorial. This tutorial shows you how you can create or build your first laravel 6 crud(create, read, update, delete) application.

This article helps you for creating crud(create, read, update, delete) application in laravel using the MySQL database. In the last of this example, we will provide a demo of this crud application.

Using this tutorial, you can easily create or build your first laravel 6 crud application.

Laravel 6 – New Crud Project With MySQL DB Example

Just follow the below steps and create your first laravel crud(create, read, update, delete) application:

  • Install Laravel Fresh New Setup
  • Setup Database Credentials
  • Generate Model and Migration
  • Create Resource Route & Controller
  • Create the blade view
  • Start Development Server
  • Conclusion

1). Install Laravel Fresh New Setup

We need to install laravel 6 fresh application using below command, Open your command prompt and run the below command :

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

After successfully install laravel 6 Application, Go to your project .env file and set up database credential and move next step.

2). Setup Database Credentials

In this step, we will set database credentials in the .env file. Let’s open .env file.

 
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

 3). Generate Model and Migration

Now we will create table name products and it’s migration file. use the below command :

php artisan make:model Product-m

It command will create one model name Product and also create one migration file for Product table. After successfully run the command go to database/migrations file and put the below here :

 
<?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->increments('id'); 
            $table->string('title'); 
            $table->string('product_code'); 
            $table->text('description'); 
            $table->timestamps(); 
        }); 
    } 
   
    /** 
     * Reverse the migrations. 
     * 
     * @return void 
     */ 
    public function down() 
    { 
        Schema::dropIfExists('products'); 
    } 
} 

Next, migrate the table using the below command.

php artisan migrate

If you found any query builder error in command prompt go to  => app\Providers\AppServiceProvider.php and put the below code here :

 use Illuminate\Support\Facades\Schema;
 
public function boot()
{
    Schema::defaultStringLength(191);
}

And then run this below command :

 php artisan migrate:fresh

Now, add the fillable property inside Product.php file.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'title',
'product_code',
'description',
];
}

4). Create Resource Route & Controller

Create the ProductController using the below command.

php artisan make:controller ProductController  --resource

This command will create a contoller name ProductController and also inside by default seven methods like index, store, create, update, destroy, show, edit.

Next, We need to add the resource route. Go to routes/web.php put the below routes here :

<?php 

Route::get('/', function () {
return view('welcome');
});

Route::resource('products', 'ProductController');

Next open controller, Go to app/HTTP/Controller/ProductController and put the below code here :

<?php
  
namespace App\Http\Controllers;
  
use App\Product;
use Illuminate\Http\Request;
use Redirect;
use PDF;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['products'] = Product::orderBy('id','desc')->paginate(10);
  
        return view('product.list',$data);
    }
   
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('product.create');
    }
  
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'product_code' => 'required',
            'description' => 'required',
        ]);
  
        Product::create($request->all());
   
        return Redirect::to('products')
       ->with('success','Greate! Product created successfully.');
    }
   
    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        
    }
   
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
        $where = array('id' => $id);
        $data['product_info'] = Product::where($where)->first();

        return view('product.edit', $data);
    }
  
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required',
            'product_code' => 'required',
            'description' => 'required',
        ]);
        
        $update = ['title' => $request->title, 'description' => $request->description];
        Product::where('id',$id)->update($update);
  
        return Redirect::to('products')
       ->with('success','Great! Product updated successfully');
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Product::where('id',$id)->delete();
  
        return Redirect::to('products')->with('success','Product deleted successfully');
    }
    
}

5). Create the blade view

We need to create some blade views files, Go to app/resources/views/ and create one folder name product. Inside the product folder create the following blade files.

Create the product folder. After successfully create product folder than create 4 following blade files.

  1. Layout.blade.php
  2. List.blade.php
  3. Create.blade.php
  4. Edit.blade.php
Layout.blade.php
<!DOCTYPE html>
<html>
  <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">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel CRUD Tutorial With Example - Tutsmake.com</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <style>
    body{
    background-color: #25274d;
    }
    .container{
    background: #ff9b00;
    padding: 4%;
    border-top-left-radius: 0.5rem;
    border-bottom-left-radius: 0.5rem;
    }
    </style>
  </head>
  <body>
    <div class="container">
      <br><br><br>
      @yield('content')
    </div>
  </body>
</html>
List.blade.php
@extends('product.layout')
  
@section('content')
  <a href="{{ route('products.create') }}" class="btn btn-success mb-2">Add</a> 
  <br>
   <div class="row">
        <div class="col-12">
         
          <table class="table table-bordered" id="laravel_crud">
           <thead>
              <tr>
                 <th>Id</th>
                 <th>Title</th>
                 <th>Product Code</th>
                 <th>Description</th>
                 <th>Created at</th>
                 <td colspan="2">Action</td>
              </tr>
           </thead>
           <tbody>
              @foreach($products as $product)
              <tr>
                 <td>{{ $product->id }}</td>
                 <td>{{ $product->title }}</td>
                 <td>{{ $product->product_code }}</td>
                 <td>{{ $product->description }}</td>
                 <td>{{ date('Y-m-d', strtotime($product->created_at)) }}</td>
                 <td><a href="{{ route('products.edit',$product->id)}}" class="btn btn-primary">Edit</a></td>
                 <td>
                 <form action="{{ route('products.destroy', $product->id)}}" method="post">
                  {{ csrf_field() }}
                  @method('DELETE')
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
                </td>
              </tr>
              @endforeach
           </tbody>
          </table>
          {!! $products->links() !!}
       </div> 
   </div>
 @endsection  
Create.blade.php
@extends('product.layout')

@section('content')
<h2 style="margin-top: 12px;" class="text-center">Add Product</a></h2>
<br>

<form action="{{ route('products.store') }}" method="POST" name="add_product">
{{ csrf_field() }}

<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <strong>Title</strong>
            <input type="text" name="title" class="form-control" placeholder="Enter Title">
            <span class="text-danger">{{ $errors->first('title') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <strong>Product Code</strong>
            <input type="text" name="product_code" class="form-control" placeholder="Enter Product Code">
            <span class="text-danger">{{ $errors->first('product_code') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <strong>Description</strong>
            <textarea class="form-control" col="4" name="description" placeholder="Enter Description"></textarea>
            <span class="text-danger">{{ $errors->first('description') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</div>

</form>
@endsection
Edit.blade.php
@extends('product.layout')

@section('content')
<h2 style="margin-top: 12px;" class="text-center">Edit Product</a></h2>
<br>

<form action="{{ route('products.update', $product_info->id) }}" method="POST" name="update_product">
{{ csrf_field() }}
@method('PATCH')

<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <strong>Title</strong>
            <input type="text" name="title" class="form-control" placeholder="Enter Title" value="{{ $product_info->title }}">
            <span class="text-danger">{{ $errors->first('title') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <strong>Product Code</strong>
            <input type="text" name="product_code" class="form-control" placeholder="Enter Product Code" value="{{ $product_info->product_code }}">
            <span class="text-danger">{{ $errors->first('product_code') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <strong>Description</strong>
            <textarea class="form-control" col="4" name="description" placeholder="Enter Description" >{{ $product_info->description }}</textarea>
            <span class="text-danger">{{ $errors->first('description') }}</span>
        </div>
    </div>
    <div class="col-md-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</div>

</form>
@endsection

6). Run Development Server

In this step, we will use the PHP artisan serve command. It will start your server locally

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/products

Conclusion

In this article, We have successfully created laravel 6 CRUD Application (Create, Read, Update, Delete) with example. Our examples run quickly.

You may like

  1. Laravel 6 Tutorial From Scratch | Step By Step
  2. Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example
  3. Laravel 6 – Ajax CRUD (Operation) Application Example
  4. Laravel 6 Angular JS CRUD Example Tutorial
  5. Upload Files/Images to Amazon s3 Cloud Using Laravel 6 Filesystem
  6. Laravel 6 CKEditor with Image Upload
  7. Ajax Image Upload In Laravel Tutorial Example From Scratch
  8. Laravel 6 Intervention Upload Image Using Ajax – Example
  9. Laravel 6 Upload Image to Database with Validation

If you have any questions or thoughts to share, use the comment form below to reach us.

One reply to Laravel 6 CRUD Example Tutorial (Step By Step)

  1. do we have a github repo for this application

Leave a Reply

Your email address will not be published. Required fields are marked *