cover image
Nitish Kumar Singh
Nitish Kumar Singh
Clock Image 6 minutes
Posted on
March 8, 2020

Laravel CRUD Operartion


Introduction #

We will be creating a form and submiting the data to the databse. Our AIM is to learn how we can fetch the data from the form and submit in the form. We will not discussing about the form data validation.

You should not keep the expectation that you will learn about the form validation.

We will break the complete article in 6 parts. In every part we will do something new and if you face some problem you can comment the step number with the error. We will be happy to help you.

Step #Task
Step 1Creating Routes
Step 2Creating Forms
Step 3Creating Controller
Step 4Creating Database Modal
Step 5Connecting to database
Step 6Saveing and Fetchind data from Database

Step 1 #

Create a new project, so that we will be on same page and there will no conflict. We will talk in same langauge and there will same default page and default data.

When you will open the routes/web.php you will see this code.

Initial Code #
routes/web.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php

/*
|--------------------------------------------------------------------------
| 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');
});
  • Create two different route.
    1. First Route will show the form.
    2. Second Route will accept the form data and savve to the database.
Updated Code #
routes/web.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php

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

Route::get('/product', function(){
    // Return the form View
    
});

Route::post('/product', function(){
    //Accept the form data
    
});

Route::put('/product/:id', function(){
    //Update data of product $id
    
});


Route::delete('/product/:id', function(){
    //Delete data of product $id
    
});

Route::get('/product/:id', function(){
    //Show data of product $id
    
});

Step 2 #

Now we have two routes, it’s time to crete the form. So, In this step we will create the form.

resources/views/product.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>

<body>
    <div class="jumbotron">
        <h1 class="text-center">
            E-commerece Wesbite
        </h1>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-md-4 offset-md-4 mt-4">
                <form action="./" method="POST">
                    <h1>Add Product</h1>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Product Name</label>
                        <input type="text" class="form-control" id="exampleInputEmail1" name="name">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Product Price</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" name="email">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Product Description</label>
                        <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="message"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</body>

</html>

Now we have a form, it’s time to show that form.

routes/web.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php

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

Route::get('/product', function(){
    // Return form View
    
});

Route::post('/product', function(){
    //Accept form data
    
});

Route::get('/products', function(){
    //Show all form response
    
});


Route::put('/product/:id', function(){
    //Update data of product $id
    
});


Route::delete('/product/:id', function(){
    //Delete data of product $id
    
});

Route::get('/product/:id', function(){
    //Show data of product $id
    
});

Now open your application and goto your localhost:8080/product. If you see the form it means you are with me.

Doing CSRF things in laravel is very easy. There is a @csrf directive which help us in protecting our website from XSS. I know this might be new for some of you that’s why I added one simple code snippet which will help you in understanding How to use CSRF in Larave ?

example-file
1
2
3
4
<form method="POST" action="/profile">
    @csrf
    ...
</form>

You just have to use @csrf inside the html form, that’s it.

After adding the @csrf token your code will look like this.

resources/views/form.html
1
2
3
4
5
6
7
8
9
<!-- Some Code -->
<form action="./" method="POST">
    @csrf
    <h1>Add Product</h1>
    <div class="form-group">
        <label for="exampleInputEmail1">Product Name</label>
        <input type="text" class="form-control" id="exampleInputEmail1" name="name">
    </div>
<!-- Some Code -->

Step 3 #

Now we will create a controller and handle all our action from there.

Terminal/Command Prompt
1
php artisan make:controller ProductController

Let’s open the controller. I hope you know the location of the controller.

app/Controllers/ProductController.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProductController extends Controller
{
    // Write Your Code Here
}

We will create total 6 method for six differnt things

Method NameFunctionality
indexShow Form
createProductSave Form Data [Create]
allProductsRead All Form Data [Read]
modifyProductModify Form Data [Update]
deleteProductDelete Form Data [Delete]
oneProductShow One Form Data
app/Controllers/ProductController.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProductController extends Controller
{
    

    function index() {
        return view('product');
    }

    function createProduct() {

    }

    function allProducts(){
        
    }


    function modifyProduct(){
        
    }


    function deleteProduct(){
        
    }


    function deleteProduct(){
        
    }
}

Now we have Controller for each routes. let’s remove the anonymous function from the web.php and update the code with controller methods.

routes/web.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php

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

Route::get('/product', 'ProductController@index');

Route::post('/product', 'ProductController@createProduct');

Route::get('/products', 'ProductController@allProducts');

Route::put('/product/:id', 'ProductController@modifyProduct');

Route::delete('/product/:id', 'ProductController@deleteProduct');

Route::get('/product/:id', 'ProductController@oneProduct');

Step 4 #

Let’s create the Migraion file.To Create the migration file using Command.

Terminal/Command Prompt
1
php artisan make:mingration create_crud_table --create=crud

When you will run the above command it will tell you then name of your migraion file. Migration file name is based on the current date, which means your file name will be not safe as mine.

Migration file is only useful it’s name is useless for us. We don’t refer this filename anywhere.

database/mingrations/2019_08_19_000000_create_crud_table.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

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

class CreateCrudTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('crud', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->int('price');
            $table->string('description');
            $table->timestamps();
        });
    }

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

Step 5 #

Step 6 #

Share this article

Comment Box

Subscribe to our Newsletter


Tweet this article