CRUD Operation in Laravel 9 using resource controller

Updated on ... 20th May 2023

In this article, I am going to create a Laravel CRUD operation using a resource controller step by step.

In this article, we will learn How to perform CRUD operation in Laravel 9 or Laravel 8 with an example.

If you have basic knowledge of PHP, you have learned about "CRUD", CRUD  refers to four basic functions of determining storage: Create, Read, Update, and Delete. It is the operations performed in the database.

Resource Controller: 

Simply Laravel resource controllers provide the CRUD routes to the controller in a single line of code. or we can say single resource route in web.php


CRUD Operation in Laravel 9 using resource controller

CRUD operations Laravel is a simple and basic task to perform even for beginners. 

Laravel CRUD operation can be easily performed with the help of the following steps:

  • Step 01:  Create laravel projects and setup the database in .env file 
  • Step 02:  Create Migration 
  • Step 03:  Create a resource controller 
  • Step 04:  Create resource route
  • Step 05: create an index method in our controller
  • Step 06: create index.blade.php 
  • Step 07: create  create method in our controller
  • Step 08: create  edit method in our controller
  • Step 09: create edit.blade.php 
  • Step 10: create  update method in our controller
  • Step 11: create  update delete method in our controller


Step 01:  Create Laravel projects and set up the database in .env file 

First you have to craete a laravel projects using  below command

composer create-project laravel/laravel example-app

Now you can run your projects using below command 

php artisan serve
Open your browser and type url http://127.0.0.1:8000/ If every thing will be fine, you will see the welcome page



And now you have to  set up your env file like below


                                                    

                                                    

                                                    DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crud_resource2
DB_USERNAME=root
DB_PASSWORD=databasepasswordifany

                                                    

                                                

Step 02:  Create migration and run it 

Now we will create a model file using the command and will pass the migration  flag (-m) too, at a time it will create two files one is inside the project folder -> database->migrations  and another will be inside the project folder -> app -> Models 

Command for creating migration and modal at a time

php artisan make:model Post -m  

Now we will create schema in the migration file for creating the posts table, Just copy and paste the below code in the migration file.


                                                    

                                                    

                                                    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->longText('content')->nullable();
            $table->string('meta_keywords')->nullable();
            $table->integer('status')->default(0);
            $table->timestamps();
        });
    }

                                                    

                                                

You Should Also Read

Step 03:  Create a resource controller

Now we will create a PostController and will pass a --resource flag for creating a resource controller. run the below command for creating a resource controller:

php artisan make:controller PostControler --resource

Resource Controller: is nothing but it provides crud related to all methods by default and we can create all routes by writing a single line of codes which is Route::resource();


Now open the PostController.php file and call the Post model and write all needed functions one by one or  just copy and paste the below code





                                                    

                                                    

                                                    <?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    
    public function index()
    {
        $post =  Post::get()->all();
        return view('post.index', compact('post'));
    }

    /**
     * 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)
    {
        $post = new Post();
    
        $post->title =  $request->input('title');
        $post->content =  $request->input('content');
        $post->status =  $request->input('status');

        $post->save();

        return redirect()->route('post.index')->with('message', 'Post added successfully');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

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

        $post = Post::find($id);
        return view('post.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, $id)
    {
        $post = Post::find($id);

        $post->title =  $request->input('title');
        $post->content =  $request->input('content');
        $post->status =  $request->input('status');

        $post->save();

        return redirect()->route('post.index')->with('message', "post updated successfully");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $post = Post::find($id);

        $post->delete();
        return redirect()->route('post.index')->with('message', 'Post deleted dsuccesssfully');

    }
}

                                                    

                                                

Step 04:  Create a resource route

As above describe a route provide a single URL but a resource route provides all crud-related routes.

we can create a resource route like Route::resource();

Now open web.php and copy and paste the below code.


                                                    

                                                    

                                                    <?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::get('/', function () {
    return view('welcome');
});


Route::resource('/post', PostController::class);

                                                    

                                                

Step 05: create all view blade file one by one

now we will create all view-related blade files inside the project folder -> resources -> views -> post

we are using bootstrap CDN for better looks.

index.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 Crud operation</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>

<body>
    <div class="container p-3">
        <div class="row">

            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-6">
                        <h2>Laravel 9 Crud operation</h2>
                    </div>
                    <div class="col-md-6 text-end"> <a href="{{ route('post.create') }}" class="btn btn-primary">Create
                            New
                            post</a></div>
                </div>

                @if (session('message'))
                    <h3 style="color:green">{{ session('message') }}</h3>
                @endif
            </div>

            <div class="col-md-12">

                <table class="table">
                    <thead>
                        <tr>
                            <td>#</td>
                            <td>title</td>
                            <td>content</td>
                            <td>status</td>
                            <td>action</td>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $num = 1;
                        @endphp

                        @foreach ($post as $post)
                            <tr>
                                <td>{{ $num++ }} </td>
                                <td>{{ $post->title }} </td>
                                <td>{{ $post->content }} </td>
                                <td>{{ $post->status }} </td>
                                <td>
                                    <div class="d-flex">
                                        <a href="{{ route('post.edit', $post->id) }}"
                                            class="btn btn-primary me-3">edit</a>

                                        <form action="{{ route('post.destroy', $post->id) }}" method="post"
                                            class="">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-danger">delete</button>
                                        </form>
                                    </div>

                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>

            </div>
        </div>

    </div>

</body>

</html>

                                                    

                                                

Now open your browser and type URL  http://127.0.0.1:8000/post  if everything is fine, you will see the below screen.

Now we will create.blade.php file  inside views -> post folder




                                                    

                                                    

                                                    <!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 Crud operation</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>

<body>
    <div class="container p-3">
        <div class="row">

            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-6">
                        <h2>Laravel 9 Crud operation</h2>
                    </div>
                    <div class="col-md-6 text-end"> <a href="{{ route('post.create') }}" class="btn btn-primary">Create
                            New
                            post</a></div>
                </div>

                @if (session('message'))
                    <h3 style="color:green">{{ session('message') }}</h3>
                @endif
            </div>

            <div class="col-md-12">

                <table class="table">
                    <thead>
                        <tr>
                            <td>#</td>
                            <td>title</td>
                            <td>content</td>
                            <td>status</td>
                            <td>action</td>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $num = 1;
                        @endphp

                        @foreach ($post as $post)
                            <tr>
                                <td>{{ $num++ }} </td>
                                <td>{{ $post->title }} </td>
                                <td>{{ $post->content }} </td>
                                <td>{{ $post->status }} </td>
                                <td>
                                    <div class="d-flex">
                                        <a href="{{ route('post.edit', $post->id) }}"
                                            class="btn btn-primary me-3">edit</a>

                                        <form action="{{ route('post.destroy', $post->id) }}" method="post"
                                            class="">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-danger">delete</button>
                                        </form>
                                    </div>

                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>

            </div>
        </div>

    </div>

</body>

</html>

                                                    

                                                

Now open your browser and type URL  http://127.0.0.1:8000/post/create or click on create new post button you will see the below screen.

Now we will add some test posts so that we will test them by editing and deleting them.

I hope it is working fine.

Now we will create an edit.blade.php file inside views -> post folder


                                                    

                                                    

                                                    <!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>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>

<body>

    <div class="container p-3">
        <div class="row d-flex justify-content-center">

            <div class="col-md-6 p-3 border">

                <h2>Edit post</h2>

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

                    <div class="mb-3">
                        <label for="title" class="form-label">Title</label>
                        <input type="text" name="title" id="title" class="form-control"
                            value="{{ $post->title }}">
                    </div>
                    <div class="mb-3">
                        <label for="content" class="form-label">Content</label>
                        <input type="text" name="content" id="content" class="form-control"
                            value="{{ $post->content }}">
                    </div>
                    <div class="mb-3">
                        <label for="status" class="form-label">status</label>
                        <select name="status" id="status" class="form-select">
                            <option value="0" {{ $post->status == 0 ? 'selected' : '' }}>0</option>
                            <option value="1" {{ $post->status == 1 ? 'selected' : '' }}>1</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-primary">save</button>

                </form>


            </div>
        </div>
    </div>

</body>

</html>

                                                    

                                                

Now open your browser and type URL  http://127.0.0.1:8000/post/1/edit or click on the edit button you will see the below screen.


and we have already created all methods above in our controller so that the delete button will work fine.

Hope you have created your crud operation in laravel using the resource controller and Resource route.

Note: If is there anything left or you have any error you can comment below I will reply your comment as soon as possible.



Related Post

Leave a comment

  • ...
    abdul

    ssadsd