# Laravel 8 CRUD Tutorial Step By Step

## Laravel 8 CRUD Tutorial Step By Step

Laravel 8 crud example tutorial. In this post, i will show you from scratch on how to build/make simple crud application in laravel 8 with validation.

The crud means create, read, update and delete records from database.

In this example post, i will create blog post crud (create , read, update and delete) app in laravel with validation.

This tutorial will completely guide you from scratch to create crud app in laravel 8 for beginners.

### Laravel 8 CRUD – Simple CRUD Example Tutorial

* Step 1 – Install **Laravel 8** Application
* Step 2 – Configuring Database using Env File
* Step 3 – Create Post Model & Migration
* Step 4 – Create Routes
* Step 5 – Creating Resource Controller
* Step 6 – Create Blade Views File
* Step 7 – Start Development Server
* Step 8 – Run Laravel 8 CRUD App On Browser

#### Step 1 – Install Laravel 8 Application <a href="#block-3e90f74b-c260-4f9f-9c76-50486e33e39f" id="block-3e90f74b-c260-4f9f-9c76-50486e33e39f"></a>

In step 1, open your terminal and navigate to your local web server directory using the following command:

```
//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html
```

Then install laravel 8 latest application using the following command:

```
composer create-project --prefer-dist laravel/laravel Laravel8Crud
```

#### Step 2 – Configuring Database using Env File <a href="#block-dfc0d863-efd0-4b4d-abe3-7a049a540d88" id="block-dfc0d863-efd0-4b4d-abe3-7a049a540d88"></a>

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like&#x20;

```
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
```

#### Step 3 – Create Post Model & Migration <a href="#block-c11eac42-987a-4b02-a09c-d7d51d413d6a" id="block-c11eac42-987a-4b02-a09c-d7d51d413d6a"></a>

In step 3, open command prompt and navigate to your project by using the following command:

```
cd / Laravel8Crud
```

Then create model and migration file by using the following command:

```
php artisan make:model Post -m
```

The above command will create two files into your laravel 8 form validation application, which is located inside the following locations:

* Laravel8Crud/app/Models/Post.php
* Laravel8Crud/database/migrations/create\_posts\_table.php

Now, find **Post.php** model file inside Laravel8Crud/app/Models directory. And open it then add the fillable property code into **Post.php** file, like following:

```
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'description'
    ];
}
```

Then, find **create\_posts\_table.php** file inside **Laravel8Crud/database/migrations/** directory. Then open this file and add the following code into **function up()** on this file:&#x20;

```
 public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }
```

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

```
php artisan migrate
```

#### Step 4 – Create Routes <a href="#block-cc160ab4-1109-4d83-990b-a40870e946f1" id="block-cc160ab4-1109-4d83-990b-a40870e946f1"></a>

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

```
use App\Http\Controllers\PostCRUDController;

Route::resource('posts', PostCRUDController::class);
```

#### Step 5 – Creating Resource Controller <a href="#block-65b5adf7-3225-4251-b8bd-90aa8dad9998" id="block-65b5adf7-3225-4251-b8bd-90aa8dad9998"></a>

In step 5, create resource controller by using the following command:

```
php artisan make:controller PostCRUDController --resource
```

The above command will create **PostCRUDController.php** file, which is located inside **LaravelForm/app/Http/Controllers/** directory.

The following laravel validation rules will validate form data before store into database in laravel:&#x20;

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

So open PostCRUDController.php file and add the following code into it:

```
<?php
  
namespace App\Http\Controllers;
   
use App\Models\Post;
use Illuminate\Http\Request;
  
class PostCRUDController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['posts'] = Post::orderBy('id','desc')->paginate(5);
    
        return view('posts.index', $data);
    }
     
    /**
     * 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 has been created successfully.');
    }
     
    /**
     * Display the specified resource.
     *
     * @param  \App\post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        return view('posts.show',compact('post'));
    } 
     
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\post  $post
     * @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  \App\post  $post
     * @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  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();
    
        return redirect()->route('posts.index')
                        ->with('success','Post has been deleted successfully');
    }
}
```

#### Step 6 – Create Blade Views File <a href="#block-3c82f583-a989-4f6e-8744-b531075994c4" id="block-3c82f583-a989-4f6e-8744-b531075994c4"></a>

In step 6, create one directory name **posts** inside **resource/views** directory. Then create new 3 blade views file that named **create.blade.php, edit.blade.php and index.blade.php** inside **resources/views/posts directory**.

The following code display error message in laravel add and edit blog post forms. So do not forget to add the following code laravel add edit blog posts forms:

```
  @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
```

Don’t worry i have already added the validation error message display code along with each form fields.

So, you can add the following php and html form code into **create.blade.php, edit.blade.php and index.blade.php**:

**posts/create.blade.php**

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Blog Post Form - Laravel 8 CRUD Tutorial</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
</head>
<body>

<div class="container mt-2">
  
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left mb-2">
            <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>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('posts.store') }}" method="POST">
    @csrf
  
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Post Title:</strong>
                <input type="text" name="title" class="form-control" placeholder="Post Title">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Post Description:</strong>
                <textarea class="form-control" style="height:150px" name="description" placeholder="Post Description"></textarea>
            </div>
        </div>
        <button type="submit" class="btn btn-primary ml-3">Submit</button>
    </div>
   
</form>

</body>
</html>
```

**posts/edit.blade.php**

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Blog Post Form - Laravel 8 CRUD Tutorial</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
</head>
<body>

<div class="container mt-2">

    <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>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('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>Post Title:</strong>
                    <input type="text" name="title" value="{{ $post->title }}" class="form-control" placeholder="Post Title">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Post Description:</strong>
                    <textarea class="form-control" style="height:150px" name="description" placeholder="Post Description">{{ $post->description }}</textarea>
                </div>
            </div>
            
              <button type="submit" class="btn btn-primary ml-3">Submit</button>
          
        </div>
   
    </form>
</div>

</body>
</html>
```

**posts/index.blade.php**

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 8 CRUD Tutorial</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
</head>
<body>

<div class="container mt-2">

<div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 8 Post CRUD Tutorial</h2>
            </div>
            <div class="pull-right mb-2">
                <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>S.No</th>
            <th>Title</th>
            <th>Description</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($posts as $post)
        <tr>
            <td>{{ $post->id }}</td>
            <td>{{ $post->title }}</td>
            <td>{{ $post->description }}</td>
            <td>
                <form action="{{ route('posts.destroy',$post->id) }}" method="POST">
    
                    <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() !!}

</body>
</html>
```

#### Step 7 – Start Development Server <a href="#block-f8b89b44-2fd8-4d37-8f9f-ebcdaf4ed326" id="block-f8b89b44-2fd8-4d37-8f9f-ebcdaf4ed326"></a>

Finally, open your command prompt again and run the following command to start development server for your simple laravel 8 crud app:

```
php artisan serve
```

#### Step 8 – Run Laravel 8 CRUD App On Browser <a href="#block-2e323e2d-f50d-46d5-ad47-ac7fa356b036" id="block-2e323e2d-f50d-46d5-ad47-ac7fa356b036"></a>

In step 8, open your browser and fire the following url into your browser:

```
http://127.0.0.1:8000/posts
```

When you fire the above given url on browser, simple laravel 8 crud app will look like in the following images:![](https://laratutorials.com/wp-content/uploads/2020/09/laravel-8-crud-1024x452.png)![](https://laratutorials.com/wp-content/uploads/2020/09/laravel-8-crud-add-blog-post-form-1024x392.png)![](https://laratutorials.com/wp-content/uploads/2020/09/laravel-8-crud-update-blog-post-form-1024x392.png)
