Angularjs Crud In Laravel 8 Tutorial

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
Angularjs Crud In Laravel 8

Hello Dev’s
Today in this blog, I will give you a example of how to do angularjs crud in laravel 8 application.

Here we will use angularjs to perform our CRUD operation(Create, Read, Update, Delete) easily in laravel 8 application.

Now here we will make a very simple crud example for item module. If you are fresher in angularjs than I hope you don’t need to worry about this because here i will present it as simple as possible.

Just need to follow below step to perform CRUD by using angularjs in your laravel 8 application:

Install Laravel 8

Here we need to create laravel 8 fresh application.

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

Create Item Table

Now in this step we will create a migration for item table. By using this command and also need to put bellow code in migration file

php artisan make model:item -m

Need to put this code on item Model

app/Model/item.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $table = 'item';

    protected $fillable = [
        'name', 'quantity', 'price'
    ];
}

Now need to replace code bellow

<?php

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

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

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

Create Controller

By Run below command in terminal to make a new item controller :

php artisan make:controller API/ItemController --api

app/controller/API/ItemController.php

Now just update ItemController as like as below :

<?php
 
namespace App\Http\Controllers\API;
 
use App\Model\Item;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\ModelNotFoundException;
 
class ItemController extends Controller
{
    public function index()
    {
        return response()->json([
            'error' => false,
            'items'  => Item::all(),
        ], 200);
    }
 
    public function store(Request $request)
    {
        $validation = Validator::make($request->all(),[ 
            'name' => 'required',
            'quantity' => 'required',
            'price' => 'required',
        ]);
 
        if($validation->fails()){
            return response()->json([
                'error' => true,
                'messages'  => $validation->errors(),
            ], 200);
        }
        else
        {
            $item = new Item;
            $item->name = $request->input('name');
            $item->quantity = $request->input('quantity');
            $item->price = $request->input('price');
            $item->save();
     
            return response()->json([
                'error' => false,
                'item'  => $item,
            ], 200);
        }
    }
 
    public function show($id)
    {
        $item = Item::find($id);
 
        if(is_null($item)){
            return response()->json([
                'error' => true,
                'message'  => "Record with id # $id not found",
            ], 404);
        }
 
        return response()->json([
            'error' => false,
            'item'  => $item,
        ], 200);
    }
 
    public function update(Request $request, $id)
    {
        $validation = Validator::make($request->all(),[ 
            'name' => 'required',
            'quantity' => 'required',
            'price' => 'required',
        ]);
 
        if($validation->fails()){
            return response()->json([
                'error' => true,
                'messages'  => $validation->errors(),
            ], 200);
        }
        else
        {
            $item = Item::find($id);
            $item->name = $request->input('name');
            $item->quantity = $request->input('quantity');
            $item->price = $request->input('price');
            $item->save();
     
            return response()->json([
                'error' => false,
                'item'  => $item,
            ], 200);
        }
    }
 
    public function destroy($id)
    {
        $item = Item::find($id);
 
        if(is_null($item)){
            return response()->json([
                'error' => true,
                'message'  => "Record with id # $id not found",
            ], 404);
        }
 
        $item->delete();
     
        return response()->json([
            'error' => false,
            'message'  => "Item record successfully deleted id # $id",
        ], 200);
    }
}

routes/api.php

Route::group(['prefix' => 'api/v1','namespace' => 'API'], function(){
    Route::apiResource('items', 'ItemController');  
});

public/app/app.js

Need to Create app.js file and put below code :

var app = angular.module('itemRecords', [])
        .constant('API_URL', 'http://localhost:8000/api/v1/');

/public/app/controllers/items.js

Create items.js file and put below code :

app.config(function ($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
});

app.controller('itemsController', function ($scope, $http, API_URL) {
     
    //fetch items listing from 
 
    $http({
        method: 'GET',
        url: API_URL + "items"
    }).then(function (response) {
        $scope.items = response.data.items;
        console.log(response);
    }, function (error) {
        console.log(error);
        alert('This is embarassing. An error has occurred. Please check the log for details');
    });
 
    //show modal form
 
    $scope.toggle = function (modalstate, id) {
        $scope.modalstate = modalstate;
        $scope.item = null;
 
        switch (modalstate) {
            case 'add':
                $scope.form_title = "Add New Item";
                break;
            case 'edit':
                $scope.form_title = "Item Detail";
                $scope.id = id;
                $http.get(API_URL + 'items/' + id)
                    .then(function (response) {
                        console.log(response);
                        $scope.item = response.data.item;
                    });
                break;
            default:
                break;
        }
         
        console.log(id);
        $('#myModal').modal('show');
    }
 
    //save new record and update existing record
    $scope.save = function (modalstate, id) {
        var url = API_URL + "items";
        var method = "POST";
 
        //append item id to the URL if the form is in edit mode
        if (modalstate === 'edit') {
            url += "/" + id;
 
            method = "PUT";
        }
 
        $http({
            method: method,
            url: url,
            data: $.param($scope.item),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(function (response) {
            console.log(response);
            location.reload();
        }), (function (error) {
            console.log(error);
            alert('This is embarassing. An error has occurred. Please check the log for details');
        });
    }
 
    //delete record
    $scope.confirmDelete = function (id) {
        var isConfirmDelete = confirm('Are you sure you want this record?');
        if (isConfirmDelete) {
 
            $http({
                method: 'DELETE',
                url: API_URL + 'items/' + id
            }).then(function (response) {
                console.log(response);
                location.reload();
            }, function (error) {
                console.log(error);
                alert('Unable to delete');
            });
        } else {
            return false;
        }
    }
});

index.blade.php

Now we will create index.blade.php and put below code :

<!doctype html>
<html lang="en" ng-app="itemRecords">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1,
            shrink-to-fit=no">
 
        <!-- Bootstrap CSS -->
        <link rel="stylesheet"
            href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
            integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
            crossorigin="anonymous">
 
        <title>Laravel 8 Crud application Angular JS Tutorial</title>
    </head>
    <body>
        <div class="container" ng-controller="itemsController">
            <header>
                <h2>items Database</h2>
            </header>
            <div>
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Quantity</th>
                            <th>Price</th>
                            <th><button id="btn-add" class="btn btn-primary
                                    btn-xs"
                                    ng-click="toggle('add', 0)">Add New item</button></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="item in items">
                            <td>[[ item.id ]]</td>
                            <td>[[ item.name ]]</td>
                            <td>[[ item.quantity ]]</td>
                            <td>[[ item.price ]]</td>
                            <td>
                                <button class="btn btn-default btn-xs
                                    btn-detail"
                                    ng-click="toggle('edit', item.id)">Edit</button>
                                <button class="btn btn-danger btn-xs btn-delete"
                                    ng-click="confirmDelete(item.id)">Delete</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- Modal -->
            <div class="modal fade" id="myModal" tabindex="-1"
                role="dialog" aria-labelledby="exampleModalLabel"
                aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">[[ form_title ]]</h5>
                            <button type="button" class="close"
                                data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <form name="frmitems" class="form-horizontal"
                                novalidate="">
 
                                <div class="form-group error">
                                    <label for="inputEmail3" class="col-sm-12
                                        control-label">Name</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control
                                            has-error" id="name" name="name"
                                            placeholder="Name"
                                            value="[[ name ]]"
                                            ng-model="item.name"
                                            ng-required="true">
                                        <span class="help-inline"
                                            ng-show="frmitems.name.$invalid
                                            && frmitems.name.$touched">Name
                                            field is required</span>
                                    </div>
                                </div>
 
                                <div class="form-group">
                                    <label for="inputEmail3" class="col-sm-12
                                        control-label">Quantity</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control"
                                            id="quantity" name="Quantity"
                                            placeholder="quantity"
                                            value="[[ quantity ]]"
                                            ng-model="item.quantity"
                                            ng-required="true">
                                        <span class="help-inline"
                                            ng-show="frmitems.quantity.$invalid
                                            && frmitems.quantity.$touched">Quantity field is required</span>
                                    </div>
                                </div>
 
                                <div class="form-group">
                                    <label for="inputEmail3" class="col-sm-12
                                        control-label">Price</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control"
                                            id="price"
                                            name="price"
                                            placeholder="Price"
                                            value="[[ price ]]"
                                            ng-model="item.price"
                                            ng-required="true">
                                        <span class="help-inline"
                                            ng-show="frmitems.price.$invalid
                                            &&
                                            frmitems.price.$touched">Price field is required</span>
                                    </div>
                                </div>
                                 
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary"
                                data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary"
                                id="btn-save" ng-click="save(modalstate, id)"
                                ng-disabled="frmitems.$invalid">Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
 
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <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>
 
        <!-- Load Javascript Libraries (AngularJS, JQuery, Bootstrap) -->
        <script
            src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
        <script
            src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular-animate.min.js"></script>
        <script
            src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular-route.min.js"></script>
        <!-- AngularJS Application Scripts -->
        <script src="<?= asset('app/app.js') ?>"></script>
        <script src="<?= asset('app/controllers/items.js') ?>"></script>
    </body>
</html>

Routes/web.php

In web.php file change welcome to index like this :

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

Read Also : How to Send Mail by using Mailable Class in Laravel 8?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →