Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

In this tutorial, we'll learn how to create crud example with laravel 8. we are going to show you step by step from scratch so, i will better to understand if you are new in laravel.

Install Laravel 8

first of all we need to get fresh Laravel 8 version application using bellow command:

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

 

Database Configuration

In second step, we will make database configuration. 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=laravel8_db
DB_USERNAME=laravel8_db
DB_PASSWORD=laravel8_db

 

Create Migration

we're going to create crud expamle for posts. so we have to create migration for posts table using Laravel 8 php artisan command, as bellow command:

php artisan make:migration create_posts_table --create=posts

this command will generate file in the following path database/migrations and you have to put bellow code in your migration file for create posts table.

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

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

 

Now you have to run this migration using this command:

php artisan migrate

 

Add Routes in routes/web.php

now we need to add routes for posts crud application. so open your routes/web.php file and add the following route.

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

 

Add Model and Controller

In this step, now we should create new controller as PostController. So run bellow command and create new controller. bellow controller for create resource controller.

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

this command you will generate new controller PostController.php and new model Post.php.

So, let's copy bellow code and put on PostController.php file.

<?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()
    {
        $posts = Post::latest()->paginate(10);

        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',
            'content' => 'required',
        ]);

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

        return redirect()->route('posts.index')
            ->with('message','Post added 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',
            'content' => 'required',
        ]);

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

        return redirect()->route('posts.index')
            ->with('message','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('message','Post deleted successfully');
    }
}

 

also put bellow content in app/Post.php file:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'title', 'content'
    ];

}

 

Add THEME Files 

In this step we have to create just 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:

  • layout.blade.php
  • index.blade.php
  • create.blade.php
  • edit.blade.php
  • show.blade.php

So let's just create following files.

create resources/views/layout.blade.php file:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 tutos</title>

    {{-- style  files --}}
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>
<body>

<div class="container">
    @yield('content')
</div>


{{-- script files --}}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>
</html>

 

create resources/views/posts/index.blade.php file:

@extends('layout')

@section('content')
    <div class="row">
        <div class="col-12 my-5">
            <div class="float-left">
                <h2>List Posts</h2>
            </div>
            <div class="float-right">
                <a class="btn btn-primary" href="{{ route('posts.create') }}"> Add Post </a>
            </div>
        </div>
    </div>

    @if(Session::has('message'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            {!! Session::get('message') !!}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <table class="table">
        <thead class="thead-light">
            <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Content</th>
                <th>Operations</th>
            </tr>
        </thead>
        <tbody>
        @foreach ($posts as $post)
            <tr>
                <td>{{ $post->id }}</td>
                <td>{{ $post->title }}</td>
                <td>{{ $post->content }}</td>
                <td>

                    <form action="{{ route('posts.destroy',$post->id) }}" method="POST">
                        @csrf
                        @method('DELETE')
                        <a class="btn btn-info btn-sm" href="{{ route('posts.show',$post->id) }}">View</a>
                        <a class="btn btn-primary btn-sm" href="{{ route('posts.edit',$post->id) }}">Edit</a>
                        <button type="submit" class="btn btn-danger btn-sm"
                                onclick="return confirm('are you sure you want to delete this post')">
                            Delete
                        </button>
                    </form>
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>

   <div class="row">
       <div class="col-12 d-flex ">
           <div class="pagination mx-auto">
           {!! $posts->links() !!}
           </div>
       </div>
   </div>

@endsection

 

create resources/views/posts/create.blade.php file:

@extends('layout')

@section('content')
    <div class="row">
        <div class="col-12 my-5">
            <div class="float-left">
                <h2>Add Post</h2>
            </div>
            <div class="float-right">
                <a class="btn btn-primary" href="{{ route('posts.index') }}"> List posts </a>
            </div>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <form action="{{ route('posts.store') }}" method="POST">
        @csrf
            <div class="form-group">
                <label for="title">Title</label>
                <input id="title" type="text" name="title" class="form-control" placeholder="Title...">
            </div>

            <div class="form-group">
                <label for="content">Content</label>
                <textarea class="form-control" id="content" name="content" placeholder="Content..."></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Save</button>
    </form>
@endsection

 

create resources/views/posts/edit.blade.php file:

@extends('layout')

@section('content')

    <div class="row">
        <div class="col-12 my-5">
            <div class="float-left">
                <h2>Edit Post</h2>
            </div>
            <div class="float-right">
                <a class="btn btn-primary" href="{{ route('posts.index') }}"> List posts </a>
            </div>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <form action="{{ route('posts.update',$post->id) }}" method="POST">
        @csrf
        @method('PUT')

        <div class="form-group">
            <label for="title">Title</label>
            <input id="title" type="text" name="title" value="{{ $post->title }}" class="form-control" placeholder="Title...">
        </div>

        <div class="form-group">
            <label for="content">Content</label>
            <textarea class="form-control" id="content" name="content" placeholder="Content...">
                {!! $post->content !!}
            </textarea>
        </div>

        <button type="submit" class="btn btn-primary">Save</button>
    </form>
@endsection

 

create resources/views/posts/show.blade.php file:

@extends('layout')
@section('content')
    <div class="row">
        <div class="col-12 my-5">
            <div class="float-left">
                <h2>Show Post</h2>
            </div>
            <div class="float-right">
                <a class="btn btn-primary" href="{{ route('posts.index') }}"> List posts </a>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">{{ $post->title }}</h5>
                    <p class="card-text">{!! $post->content !!}</p>

                    <form action="{{ route('posts.destroy',$post->id) }}" method="POST">
                        @csrf
                        @method('DELETE')
                        <a class="btn btn-primary btn-sm" href="{{ route('posts.edit',$post->id) }}">Edit</a>
                        <button type="submit" class="btn btn-danger btn-sm"
                                onclick="return confirm('are you sure you want to delete this post')">
                            Delete
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

 

Now we are ready to run our application  so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/posts

 

You will see interfaces as like bellow:

 

get all posts:

load all posts laravel 7

 

 

Add post:

add new post laravel 7

 

Delete post:

delete post laravel 7

 

 

Edit post:

edit post laravel 7

 

Show post:

show post laravel 7

 

I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.

Comments

Add new comment

Restricted HTML

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon