Laravel 10 CRUD Application Tutorial with Example

Laravel 10 is released and some new features are coming. For checking the new updates we will see in CRUD operation with Laravel 10 application. Here we have added the Laravel 10 CRUD Tutorial with Example. CRUD is a basic and main topic to understand any application so we have added a simple and step by step CRUD operation in Laravel 10 from scratch.

Using this Laravel 10 CRUD operation tutorial you will learn how to build a simple crud operation app in Laravel 10 and how to validate with store & update form data to the database with bootstrap and MySQL.

Laravel 10 CRUD Operation Step by Step

Here is the following topics we will implement to make the laravel 10 crud application easy wa.

  • Step 1: Download Laravel 10 App
  • Step 2: Connect Database to App
  • Step 3: Create Model & Migration
  • Step 4: Add Routes
  • Step 5: Create a Controller
  • Step 6: Create Blade Files
  • Step 7: Run Laravel Application

Step 1: Download Laravel 10 App

First of all,, we will download a new laravel 10 application. For installing laravel application we will open the terminal and run the below command.

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

The above command generates a laravel app for your located location.

Now go into the app:

cd laravel-crud

Step 2: Connect Database to App

In the second step you need to setup your database credentials with our application. You just need to create a database and update it in the .env file just like below. The .env file is stand in your root directory.

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

Step 3: Create Model & Migration for CRUD

Now it the time to create a model and migration file just adding the below command in your terminal which generates a model file and migration which will show your database table after running the migration command.

php artisan make:model Post -m

Now you can see in your database migration directory created a new file same as below, here you need to add you database columns.

database\migrations\2020_09_13_071913_create_projects_table.php

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

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

After adding the columns now run the below command which is generate table in your database.

php artisan migrate

Add Fillable Property: In your app/models inside generated a new file Post.php file where you need to add fillable properties.

app\Models\Post.php

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
      'title', 'body'
    ];
}

Step 4: Make Routes for Laravel CRUD

Now here we will make routes for our laravel 10 crud application. For this you need to open your “routes/web.php” file and your routes same as below.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/', function () {
    return view('welcome');
});

Step 5: Create a controller

After adding the routes files now its time to create a new controller for handle the Laravel 10 CRUD operation logic. For this you just need to add below command and generate a new resource controller PostController.

php artisan make:controller PostController --resource

After running this command you will find a new file in this path “app/Http/Controllers/PostController.php” where you can see the CRUD opearation methods already created like below.

  • index() => Show the list of data
  • create() => Show form for create new record
  • store() => Store record in the database
  • show() => Show a specific record
  • edit() => show the edit form
  • update() => Update the existing record
  • destroy() => delete the record

So, open the “PostController.php” file and just copy and paste the following code into it.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

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

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

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

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\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\Models\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\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        $request->validate([
            'title' => 'required',
            'body' => 'required',
        ]);

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
      $post->delete();

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

Step 6: Create Blade View Files

Now is the time to create the blade view files. First, create two folders one is “layouts” and another is “posts”. In layout, the folder creates app.blade.php file, and inside the posts folder create another blade file. 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:

  • resources/views/layouts/app.blade.php
  • resources/views/posts/index.blade.php
  • resources/views/posts/create.blade.php
  • resources/views/posts/edit.blade.php
  • resources/views/posts/show.blade.php

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

resources/views/layouts/app.blade.php

This is the file which extends the all files of our application.

<!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

This file show the list of post which is crated already.

@extends('layouts.app')
@section('content')

    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 9 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>Body</th>
        </tr>
        @foreach ($posts as $post)
        <tr>
            <td>{{ $post->title }}</td>
            <td>{{ $post->body }}</td>
            <td>
                 <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>
                <form action="{{ route('posts.destroy',$post->id) }}" method="POST">
   
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>

@endsection

resources/views/posts/create.blade.php

The create file shows the form where user creates a post.

@extends('layouts.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>Body:</strong>
                <textarea class="form-control" style="height:150px" name="body" placeholder="Post Body"></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

This page will show users to edit there post.

@extends('layouts.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>Body:</strong>
                    <textarea class="form-control" style="height:150px" name="body" placeholder="Post Body">{{ $post->body }}</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

This page will show or preview the post.

@extends('layouts.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>Body:</strong>
                {{ $post->body }}
            </div>
        </div>

    </div>
@endsection

Step 7: Run your CRUD App

Finally, Laravel 10 CRUD Example Tutorial For Beginners From Scratch is over. In this CRUD app. Let’s run this crud application example with laravel 10 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

Today we have learned laravel 10 CRUD app example. I hope you enjoy this.