Laravel 6 CRUD Tutorial with Example

In this example, I will show you to how to make simple laravel CRUD(insert, update, delete or listing) operations with example.

Insert Update Delete module is primary requirement for each project,you will understand how to use route, controller, blade files, model and migration for crud operation in laravel 6.

We just need to follow below step and you will get basic CRUD using controller, model, route, bootstrap 4 and blade. If you follow below step then definatly you will get proper output.

So,let's start

Step 1 - Create/install New Laravel Project
Step 2 - Setup Database
Step 3 - Create Model and Migration
Step 4 - Create Controller
Step 5 - Create Blade Files
Step 6 - Run Project in Browser

 

Step 1 : Install  Laravel  6 

Type the following command in terminal.

composer create-project --prefer-dist laravel/laravel blog "6.*"

 

Step 2: Database Configuration

In second step, we will setup database configuration for example database name, username, password etc for our crud application of laravel 6. So let's open .env file and fill all details like as bellow: 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name(blog)
DB_USERNAME=your database username(root)
DB_PASSWORD=your database password(root)

 

 

Step 3: Create Migration and model

We are going to create crud application for post. so we have to create migration for "posts" table using Laravel 6 php artisan command, so first type below command:

php artisan make:migration create_posts_table --create=posts

 

After run this command you will find php file here location "database/migrations/" in this file you need to add below code.

<?php 

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

class CreatePostsTable extends Migration { 

/** 
* Run the migrations. 
* 
* @return void */ 

public function up() 
{ 
    Schema::create('posts', function (Blueprint $table) { 
            $table->bigIncrements('id');
            $table->string('name')->nullable();
            $table->longText('detail')->nullable();
            $table->timestamps();
        });
    }

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

Now you have to run this migration by following command:

php artisan migrate

 

Step 4: Add Resource Route

Now Add Resource route in Routes/web.php

Route::resource('posts','PostController');

 

Step 5: Add Controller and Model

create the PostController using the following command.

php artisan make:controller PostController --resource --model=Post

Now make changes in Model , you will find model in this folder App/Post.php add below code in post.php

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
   
class Post extends Model
{
    protected $fillable = [
        'id', 'name', 'detail'
    ];
}

 

 

After changes in model you will find PostController.php in this path app/Http/Controllers/PostController.php. In this controller will create 7 methods by default as below methods:

So,Copy below code in your post controller

<?php
  
namespace App\Http\Controllers;
  
use App\Post;
use Illuminate\Http\Request;
  
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::latest()->paginate(5);
  
        return view('post.index',compact('post'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }
   
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('post.create');
    }
  
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
  
        Post::create($request->all());
   
        return redirect()->route('post.index')->with('success','Post created successfully.');
    }
   
    /**
     * Display the specified resource.
     *
     * @param  \App\Post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        return view('post.show',compact('post'));
    }
   
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\post
     * @return \Illuminate\Http\Response
     */
    public function edit(Post $post)
    {
        return view('post.edit',compact('post'));
    }
  
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
  
        $post->update($request->all());
  
        return redirect()->route('post.index')
                        ->with('success','Post updated successfully');
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();
  
        return redirect()->route('post.index')
                        ->with('success','Post deleted successfully');
    }
}

 

Step 6: Add Blade Files

In last step. In this step we have to create blade files. So mainly we have to create layout file and then create new folder "posts" then create blade files of crud app. So finally you have to create following bellow blade file:

1) layout.blade.php

2) index.blade.php

3) create.blade.php

4) edit.blade.php

5) show.blade.php

So let's just create following file and put bellow code.

 

resources/views/posts/layout.blade.php

 

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 6 CRUD Application - techsolutionstuff.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
  
<div class="container">
    @yield('content')
</div>
   
</body>
</html>

 

 

resources/views/posts/index.blade.php

 

@extends('posts.layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 6 CRUD Example - techsolutionstuff.com</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('posts.create') }}"> Create New Post</a>
            </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>Name</th>
            <th>Details</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($posts as $post)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $post->name }}</td>
            <td>{{ $post->detail }}</td>
            <td>
                <form action="{{ route('posts.destroy',$post->id) }}" method="POST">
   
                    <a class="btn btn-info" href="{{ route('posts.show',$post->id) }}">Show</a>
    
                    <a class="btn btn-primary" href="{{ route('posts.edit',$post->id) }}">Edit</a>
   
                    @csrf
                    @method('DELETE')
      
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
  
    {!! $posts->links() !!}
      
@endsection

 

resources/views/posts/create.blade.php

 

@extends('posts.layout')
  
@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New Post</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Error!</strong> <br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ route('posts.store') }}" method="POST">
    @csrf
  
     <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="name" class="form-control" placeholder="Name">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Detail:</strong>
                <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
   
</form>
@endsection

 

resources/views/posts/edit.blade.php

 

@extends('posts.layout')
   
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit Post</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
            </div>
        </div>
    </div>
   
    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Error!</strong> <br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
  
    <form action="{{ route('posts.update',$post->id) }}" method="POST">
        @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="name" value="{{ $post->name }}" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $post->detail }}</textarea>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
              <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
   
    </form>
@endsection

 

resources/views/posts/show.blade.php

 

@extends('posts.layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Post</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
            </div>
        </div>
    </div>
   
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $post->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $post->detail }}
            </div>
        </div>
    </div>
@endsection

Now , We all completed with our code So, it's time to run this project....

So Copy below command and run in terminal.

php artisan serve

and finally you can run this project on your browser. 

http://localhost:8000/posts

 

RECOMMENDED POSTS

FEATURE POSTS