Table of contents
1.
Introduction
2.
What is CRUD in laravel?
3.
Laravel 9 CRUD Example Tutorial for Beginners
4.
Insert Operation
5.
Retrieve Operation
6.
Update Operation
7.
Delete Operation
8.
Frequently Asked Questions
8.1.
How to create CRUD API in Laravel 7?
8.2.
What is Laravel 9 CRUD?
8.3.
What are CRUD methods in API?
8.4.
What are the 4 CRUD operations?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

Create Laravel 9 CRUD Example Tutorial for Beginners

Author Rajat Agrawal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

As we know, PHP is the most popular scripting language for Web development. There are different frameworks based on PHP in the market. Laravel is one of the open-source PHP frameworks. It uses an MVC structure to develop the application using PHP and provides many functionalities for easier development of web applications.

laravel crud

In this blog, we will learn about Laravel Crud and how to perform crud operations like Create, Retrieve, Update, and Delete in Laravel. 
We will create a basic laravel crud application to understand how to perform crud operations in Laravel.

Recommended Topic, Cognizant Eligibility Criteria.

What is CRUD in laravel?

CRUD in Laravel refers to the four fundamental operations used for managing database records: Create, Read, Update, and Delete.

  • Create: It involves adding new data records to the database.
  • Read: This operation is about retrieving data from the database for viewing.
  • Update: It allows you to modify existing database records.
  • Delete: This operation is used to remove data records from the database.

Laravel provides convenient methods and tools to perform these actions easily, making managing and interacting with your application's database simpler.

Laravel 9 CRUD Example Tutorial for Beginners

We will create a product management application using Laravel and perform different CRUD operations. To create a laravel CRUD project, follow the below steps:

Step 1: First of all, we will create a laravel project named codingninjas. To create this project, run the following command in the xampp/htdocs directory.

composer create-project laravel/laravel codingninjas
You can also try this code with Online PHP Compiler
Run Code


After running the command, the codingninjas project has successfully been created in the xampp/htdocs directory. 

database in the phpMyAdmin

Step 2: Now, we will create a database in the phpMyAdmin. The name of the database is product.

phpMyAdmin

Step 3: In this step, we will make a database configuration for the example database name, username, password, etc., for our crud application. We will modify the .env file and fill in all the required details, as shown in the screenshot below: 

database in the phpMyAdmin

We have set the DB_DATABASE as productDB_USERNAME as root and left the DB_PASSWORD blank.

Step 4: Now, we will create a migration to create a table named product_items 

The command to create migration and a table is the following:

php artisan make:migration create_product_table --create="product_items"
You can also try this code with Online PHP Compiler
Run Code


After running the above command, the table will be created successfully.

output

The migration 2022_11_20_184138_create_product_table.php contains the following code:

<?php

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

return new class extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('product_items', function (Blueprint $table) {
            $table->id();
            $table->prod_name();
            $table->prod_price();
            $table->prod_brand();
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('product_items');
    }
};
You can also try this code with Online PHP Compiler
Run Code


In the above table, we have added three new columns, prod_nameprod_price, and prod_brand.

Step 5: Now, we will migrate the changes in the table into our database product. To migrate the above changes, run the following command.

php artisan migrate
You can also try this code with Online PHP Compiler
Run Code


After migrating the changes to the product database. The Product model will be created.

The Product.php file contains the following code. And also, we have added two attributes i.e., $table and $fillable

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;
    protected $table='product_items';  
    protected $fillable=['prod_name','prod_price','prod_brand'];  
}
You can also try this code with Online PHP Compiler
Run Code


Step 6: Now, we will create a controller ProductController to implement all the CRUD operations. 

To create a controller, run the following command.

php artisan make:controller ProductController -r
You can also try this code with Online PHP Compiler
Run Code


After running the above command, the controller will be created successfully.

output

The ProductController.php will contain the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProductController extends Controller
{
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index(){
    }

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

    /**
    * Store a newly created resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
    public function store(Request $request){
    }

    /**
    * 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){
    }

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

    /**
    * Remove the specified resource from storage.
    *
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
    public function destroy($id){
    }
}
You can also try this code with Online PHP Compiler
Run Code


In the above code, we can see that the ProductController contains inbuilt methods like index()create()store()show()edit()update(), and destroy(). We will use these methods to implement Laravel Crud.

 

Now, let’s implement different CRUD operations one by one.

Insert Operation

Steps to perform the insert operation are:-

Step 1: We will create a route in the web.php file to perform the insert operation.

Route::get('/insertproduct', function () {  
    return view('create');  
});  
You can also try this code with Online PHP Compiler
Run Code


Step 2: Now, we will create a view named create.blade.php in the resources/views folder.

create.blade.php

@extends('layout.master')  
@section('content')  
<form method="post" action="{{ route('products.store') }}">  
  @csrf     
          <div class="form-group">      
              <label for="prod_name">Product Name:</label><br/><br/>  
              <input type="text" class="form-control" name="prod_name"/><br/><br/>  
          </div>  
<div class="form-group">      
<label for="prod_price">Product Price:</label><br/><br/>  
              <input type="text" class="form-control" name="prod_price"/><br/><br/>  
          </div>  
<div class="form-group">      
              <label for="prod_brand">Product Brand:</label><br/><br/>  
              <input type="text" class="form-control" name="prod_brand"/><br/><br/>  
          </div> 
<br/>  
<button type="submit" class="btn-btn" >Insert Product</button>  
</form>  
@endsection  
You can also try this code with Online PHP Compiler
Run Code


Suppose we enter some data in the form and click on the Insert Product button, the data will be saved in the database. 

Output: 

output

Retrieve Operation

To perform the retrieve operation first we will create a route in the web.php file to perform the retrieve operation.

Route::get('/showproduct','ProductController@index'); 
You can also try this code with Online PHP Compiler
Run Code


The above statement creates a route with a URL '/showproduct' which calls the index( ) method of the ProductController class.  
The above route calls the index function of the ProductController and we pass the $prod object to the index.blade.php file by using the view( ) method.

index.blade.php

@extends('layout.master')  
@section('content')  
<table border="1px">  
<thead>  
<tr>  
<td>  
ID </td>  
<td>  
Product Name </td>  
<td>  
Product Price </td>  
<td>  
Product Brand </td>  
</tr>  
</thead>  
<tbody>  
@foreach($prods as $prod)  
        <tr border="none">  
            <td>{{$prod->id}}</td>  
            <td>{{$prod->prod_name}}</td>  
            <td>{{$prod->prod_price}}</td>  
            <td>{{$prod->prod_brand}}</td>    
<td >  
<form action="{{ route('products.destroy', $prod->id)}}" method="post">  
                  @csrf  
                  @method('DELETE')  
                  <button class="btn btn-danger" type="submit">Delete Product </button>  
                </form>  
</td>  
<td >  
<form action="{{ route('products.edit', $prod->id)}}" method="GET">  
                  @csrf  
                  
                  <button class="btn btn-danger" type="submit">Update Product</button>  
                </form>  
</td>  
  
        </tr>  
@endforeach  
</tbody>  
</table>  
@endsection  
You can also try this code with Online PHP Compiler
Run Code


Output: 

output

Update Operation

Steps to perform the update operation are:-

Step 1: We will click on the Update Product button created in the ‘/showproduct’ route to update the product. This will internally call the edit( ) method of the ProductController class. 

public function edit($id){  
    $prod= Product::find($id);  
    return view('edit', compact('prod'));  
}  
You can also try this code with Online PHP Compiler
Run Code


Step 2: Now, we will create a view named update.blade.php in the resources/views folder to update the product.

update.blade.php

@extends('layout.master')  
@section('content')  
<form method="Post" action="{{route('product.update',$crud->id)}}">  
@method('PATCH')     
@csrf     
          <div class="form-group">      
              <label for="prod_name">Product Name:</label><br/><br/>  
              <input type="text" class="form-control" name="prod_name" value={{$prod->prod_name}}><br/><br/>  
          </div>  
  
<div class="form-group">      
              <label for="prod_price">Product Price:</label><br/><br/>  
              <input type="text" class="form-control" name="prod_price" value={{$prod->prod_price}}><br/><br/>  
          </div>  
<div class="form-group">      
              <label for="prod_brand">Product Brand:</label><br/><br/>  
              <input type="text" class="form-control" name="prod_brand" value={{$prod->prod_brand}}><br/><br/>  
          </div>  
<br/>  
<button type="submit" class="btn-btn" >Update Product</button>  
</form>  
@endsection  
You can also try this code with Online PHP Compiler
Run Code


Suppose we enter some data in the form and click on the Update Product button, the data will be saved in the database. 

Output:

output

Delete Operation

If we click on the Delete Product button, then it calls the destroy( ) function of the ProductController class. 

The destroy( ) method contains the following code:

public function destroy($id)  
    {  
        $prod=Product::find($id);  
        $prod->delete();  
    }  
You can also try this code with Online PHP Compiler
Run Code

Must Read PHP Projects With Source Code

Frequently Asked Questions

How to create CRUD API in Laravel 7?

To create a CRUD API in Laravel 7, you can define routes, create controllers with functions for each CRUD operation (Create, Read, Update, Delete), define corresponding routes, and implement the logic for each operation using Laravel's Eloquent ORM.

What is Laravel 9 CRUD?

Laravel 9 CRUD refers to the Create, Read, Update, and Delete operations in the Laravel framework's application development, allowing manipulation of database records.

What are CRUD methods in API?

CRUD methods in API (Application Programming Interface) refer to Create, Read, Update, and Delete operations used to manage resources or data through HTTP requests.

What are the 4 CRUD operations?

The four CRUD operations are:

1. Create: Adding new data or resources.
2. Read: Retrieving or viewing existing data.
3. Update: Modifying or editing existing data.
4. Delete: Removing or eliminating existing data.

Conclusion

In this article, we have extensively discussed Laravel Crud and how to perform crud operations like Create, Retrieve, Update, and Delete in Laravel. I hope you enjoyed this blog on Laravel Crud.

Recommended Readings:


Also, check out these exciting courses from coding ninjas to expand your knowledge, Coding CourseCode StudioInterview ExperienceGuided PathInterview ProblemsTest SeriesLibrary, and Resources

Happy Coding!

Live masterclass