Laravel 6/7 CRUD tutorial with example

Websolutionstuff | May-08-2020 | Categories : Laravel PHP

In this example, I will show you how to make simple laravel CRUD(insert, update, delete, or list) operations with example. Insert Update Delete module is a primary requirement for each project, you will understand how to use the route, controller, blade files, model, and migration for crud operation in laravel 6.

In laravel 6 CRUD Operation with MySQL database. Also, it's useful for beginners. So, I will show you the laravel 6 crud tutorial with examples of crud operations in laravel 6 from scratch.

So, let's see the laravel 6/7 CRUD tutorial with example, CRUD operation in laravel 6/7, laravel 6/7 CRUD example, laravel 6/7 CRUD operation step by step, laravel 6/7 CRUD from scratch. 

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

So, let's start laravel 6 crud operation step by step.

Step 1: Create / Install Laravel 6/7 

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 the terminal.

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

 

 

Step 2: Database Configuration

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

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 the last step, we have to create blade files. So mainly we have to create layout files and then create new folder "posts" then create blade files of the crud app. So finally you have to create the 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 - websolutionstuff.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 - websolutionstuff.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 are all completed our code, it's time to run this project...

So, Copy the below command and run it in the terminal.

php artisan serve

and finally, you can run this project on your browser. 

http://localhost:8000/posts

 


You might also like :

Recommended Post
Featured Post
How To Install phpMyAdmin In Ubuntu
How To Install phpMyAdmin In U...

In this article, we will explore the process of installing phpMyAdmin in Ubuntu. phpMyAdmin is a popular web-based admin...

Read More

Jul-24-2023

How To Replace All Occurrences Of String In Javascript
How To Replace All Occurrences...

In this article, we will see how to replace all occurrences of a string in javascript. You can use the javascript r...

Read More

Nov-07-2022

How To Add jQuery Datatable Column Filter Dropdown On Top
How To Add jQuery Datatable Co...

In this article, we will see how to add a jquery datatable column filter dropdown on top. Here, we will learn how t...

Read More

Jan-19-2023

Laravel 8 REST API With Passport Authentication
Laravel 8 REST API With Passpo...

Hello Guys,  Today I will give you example of laravel 8 REST API with passport authentication. Also perform...

Read More

May-31-2021