Laravel 6 Crud Tutorial with Example for Beginners

Hello guys! Today we learn Laravel 6 CRUD example (Create, Read, Update, Delete) Step by step for beginners. Now a days Laravel is the most valuable and famous php framework and recently laravel release 6.0 version. Basically we explain Laravel 5 crud operation already in our website you can check by clicking Here. So we all know how to work crud operations in laravel, here we will demonstrate simple Laravel 6 CRUD operations step by step from scratch including how to create, update, delete, edit with database. Follow few steps to get crud application with laravel 6.

Laravel 6.0 Crud Tutorial with Example for beginners

Step 1 : Install Laravel

First we need to install fresh Laravel 6.0 application using the following command. We will use Composer Create-Project to generate laravel 6 projects.

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

Step 2: Configure MySQL Database

Now, you need to create the mysql database and connect that database to the Laravel application. You can use phpmyadmin to create the database. After creating the database, open .env file from Laravel stocks project and add the database credentials same like i have showing below.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelblog #your_database_name
DB_USERNAME=root #your_database_username
DB_PASSWORD=admin #your_database_password

Now you can add you tables easily with mysql database.

Step 3: Create a Model and Migration File

In laravel you can add a modal with migration file which is generate a model file and in database automatically create database table. If you create a modal name as Post then the database name posts created. Now creating a database table name must open your terminal and run below command.

php artisan make:model Post -m

Now in your projects folder app inside a file name as Post.php created and database>migration folder create a file same as 2019_03_23_102636_create_posts_table. Now open you migration file and add your column name which you want to add.

<?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('description')->nullable();
            $table->timestamps();
        });
    }

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

Now migrate the table using the following below command.

php artisan migrate

Add Fillable Property: After running migration command you will find “app/Post.php” and put bellow content in Post.php file:

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

Step 5: Create routes

Now you need to add resource route for post crud application. Open your “routes/web.php” file and add below code on it.

routes/web.php

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

Step 6: Create controller

After that we need to create a controller. Run below command and generate a new resource controller PostController.

php artisan make:controller PostController --resource

After running this command you will find new file in this path “app/Http/Controllers/PostController.php”. Where you saw here already created methods same like below. Now you need put below codes on your functions.

1) index() => this method get your all data from database.

2) create() => this method work creating new post.

3) store() => this method store data in your database.

3) show() => this method show the record.

3) edit() => Using this method we can edit our post.

3) update() => update method to updating the post.

7) destroy() => Using this method’s we can delete our record.

So, open you PostController.php file and put blow code on it.

app/Http/Controllers/PostController.php

<?php 

namespace App\Http\Controllers; 
use Illuminate\Http\Request; 

use App\Post; 

class PostController extends Controller 
{ 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::all();

        return view('posts.index',compact('posts'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

       return view('posts.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',
            'description' => 'required',
        ]);

        Post::create($request->all());

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        return view('posts.show',compact('post'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
     public function edit(Post $post) {

        return view('posts.edit',compact('post'));
     }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
     public function update(Request $request, Post $post) {

         $request->validate([
              'title' => 'required',
              'description' => 'required',
          ]);

          $post->update($request->all());

          return redirect()->route('posts.index')->with('success','Post updated successfully');
     }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
     public function destroy(Post $post) {

         $post->delete();

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

Step 7: Create Blade Files

Here in this step we create our view files. First create two folder one is “layout” and another is “posts”. In layout folder create app.blade.php file and and inside posts folder create another blade files. If you don’t know to integrate our blade files in laravel then please check first here how to integration laravel bootstrap admin panel.  Now create below blade files for your crud app:

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/layout/app.blade.php

<!DOCTYPE html>
<html lang="en">
<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">
  <title>Laravel 5.8 CRUD Example Tutorial</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('layout.app')
@section('content')

    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 6 CRUD Example from scratch </h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('posts.create') }}"> Create New Product</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>Title</th>
            <th>Description</th>
        </tr>
        @foreach ($posts as $post)
        <tr>
            <td>{{ $post->title }}</td>
            <td>{{ $post->description }}</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>

@endsection

resources/views/posts/create.blade.php

@extends('layout.app')
@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">
        <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="title" class="form-control" placeholder="Title">
            </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 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>
@endsection

resources/views/posts/edit.blade.php

@extends('layout.app')
@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">
            <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>Title:</strong>
                    <input type="text" name="title" value="{{ $post->title }}" class="form-control" placeholder="Title">
                </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">{{ $post->description }}</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('layout.app')
@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->title }}
            </div>
        </div>

        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Description:</strong>
                {{ $post->description }}
            </div>
        </div>

    </div>
@endsection

Finally, Laravel 6.0 CRUD Example Tutorial For Beginners From Scratch is over. In this CRUD app we used one function for create and edit. Lets run this crud application example with laravel 6 so run bellow command and see in your browser.

php artisan serve

Now you can open bellow URL on your browser: http://localhost:8000/posts So friends its very easy way to Laravel CRUD operation step by step.

Hope this tutorial help you to learning laravel 6 crud tutorial.  If you have any question regarding laravel crud operation generator then please comment below we appreciate your comment.

Leave a Comment