Site Admin
Site Admin Founder of MeaningArticles
5215 Views

Laravel 7 AngularJS CRUD Operation step by step with example

Hello Dev.

Nowadays, I will provide example of CRUD operation in Laravel 7 and AngularJS. on this articles you will learn laravel 7 and AngularJs CRUD utility with instance little by little. this article will come up with simple instance of build a laravel 7 and AngularJs CRUD utility. comply with bellow article step of laravel 7 and AngularJs CRUD operation example.this article explain you CRUD operation with code and instance.

So, permit's start few step to create instance of laravel 7 and AngularJs CRUD application. You simply want to comply with few step and you'll get fundamental CRUD stuff the use of controller, model, route, bootstrap 4 and blade.

In this article, you will examine very simple CRUD operation with laravel and AngularJs. i'm going to show you little by little from scratch so its easy to setup, it will better to recognize if you are new on laravel 7 and AngularJs.

So let's start the lesson...

AngularJS

AngularJS is a powerful JavaScript client-side Model-View-Controller (MVC) framework. it's miles particularly popular for building single page programs that behavior like AJAX application.

Laravel Angular JS CRUD Operation example

Right here same step for create laravel angular web CRUD programs follow the below steps:

-> Install Fresh Laravel 7
-> Configuration of Database
-> Create REST API Controller
-> Create a Model
-> Define Route
-> AngularJS application structure
     - AngularJS app.js
     - Create Angular js controller
-> Create blade view
-> Start development server


Step 1: Install fresh Laravel 7

First of all we want to get clean and new Laravel seven version application the use of bellow command, now open your terminal OR command prompt and then fire bellow command and run it:

composer create-project --prefer-dist laravel/laravel lara-angular


Step 2: Configuration of Database

Second step, we configure database like database name, username, password etc for CRUD application of laravel 7. let's open .env file and fill complete details equal as bellow:
.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)


Step 3: Create REST API Controller

In this step, we want to create a new controller name CustomerController. So open your command prompt and go to your project root directory than run the below given command for creat a brand new CustomerController.

php artisan make:controller API/CustomerController --api

Now go to app/controller/API/CustomerController.php and update the below methods to your controller file:
app/controller/API/CustomerController.php

<?php

namespace App\Http\Controllers\API;

use App\Customer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class CustomerController extends Controller {

    public function index() 
        {
        return response()->json(['error' => false, 'customers' => Customer::all(), ], 200);
        }

    public function store(Request $request)
        {
        $validation = Validator::make($request->all(), ['name' => 'required', 'email' => 'required|email|unique:customers,email', 'contact_number' => 'required', 'position' => 'required', ]);
        if ($validation->fails())
           {
            return response()->json(['error' => true, 'messages' => $validation->errors(), ], 200);
           } 
        else
           {
            $customer = new Customer;
            $customer->name = $request->input('name');
            $customer->email = $request->input('email');
            $customer->contact_number = $request->input('contact_number');
            $customer->save();
            return response()->json(['error' => false, 'customer' => $customer, ], 200);
           }
        }

    public function show($id) 
        {
        $customer = Customer::find($id);
        if (is_null($customer)) 
            {
            return response()->json(['error' => true, 'message' => "Record with id # $id not found", ], 404);
            }
        return response()->json(['error' => false, 'customer' => $customer, ], 200);
        }

    public function update(Request $request, $id)
        {
        $validation = Validator::make($request->all(), ['name' => 'required', 'email' => 'required|email', 'contact_number' => 'required', ]);
        if ($validation->fails())
            {
            return response()->json(['error' => true, 'messages' => $validation->errors(), ], 200);
            }
        else 
            {
            $customer = Customer::find($id);
            $customer->name = $request->input('name');
            $customer->email = $request->input('email');
            $customer->contact_number = $request->input('contact_number');
            $customer->save();
            return response()->json(['error' => false, 'customer' => $customer, ], 200);
            }
        }

    public function destroy($id) 
        {
        $customer = Customer::find($id);
        if (is_null($customer)) 
            {
            return response()->json(['error' => true, 'message' => "Record with id # $id not found", ], 404);
            }
        $customer->delete();
        return response()->json(['error' => false, 'message' => "Customer record successfully deleted id # $id", ], 200);
        }
}


Step 4: Create a Model

Now we will create one eloquent model. So go to your command prompt and run the below command:

php artisan make:model Customer

Next, go to following path app/customer.php and update the below code into your file:

customer.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model 
{
    protected $fillable = ['id', 'name', 'email', 'contact_number'];
}


Step 5: Define Route

In this step, we can define the route in routes/api.php file. So go to routes/api.php and update the below route into your file:

api.php

Route::group(['prefix' => 'v1','namespace' => 'API'], function()
{Route::apiResource('customers', 'CustomerController');  });


Step 6: AngularJS application structure

-> app – contains all AngularJS related JavaScript files
-> app/controllers – contains all AngularJS controllers
-> css – contains all CSS files
-> js – contains all regular JavaScript files for our UI.

AngularJS app.js

In this step, we are able to create a new file name app.js. So go to /public/app, create a new file name app.js and update the below code into your app.js file:

This file can be used to define our application

app.js

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

Here,
-> - var app = angular.module('customerRecords', []) creates an AngularJS module and assigns the object to the variable app. All AngularJS files will be reference the variable app

-> .constant('API_URL', 'http://localhost:8000/api/v1/'); defines a constant variable with the API URL.

Create AngularJS controllers

Now /public/app/controllers and create a controller name customers.js controller. And update the below code into your customers.js file:

customers.js

app.controller('customersController', function($scope, $http, API_URL) {
    //fetch customers listing from 
    $http({
        method: 'GET',
        url: API_URL + "customers"
    }).then(function(response) {
        $scope.customers = response.data.customers;
        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.customer = null;
        switch (modalstate) {
            case 'add':
                $scope.form_title = "Add New Customer";
                break;
            case 'edit':
                $scope.form_title = "Customer Detail";
                $scope.id = id;
                $http.get(API_URL + 'customers/' + id)
                    .then(function(response) {
                        console.log(response);
                        $scope.customer = response.data.customer;
                    });
                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 + "customers";
        var method = "POST";
        //append customer 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.customer),
            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 + 'customers/' + id
            }).then(function(response) {
                console.log(response);
                location.reload();
            }, function(error) {
                console.log(error);
                alert('Unable to delete');
            });
        } else {
            return false;
        }
    }
});

here,
-> app.controller('customersController', function($scope, $http, API_URL) {...} defines a controller employeesController in the app variable that we created in /app/app.js. We have injected $scope, $http, and a constant API_URL as dependencies

-> assigns response.employees to $scope.customersvariable. The $scope.customersvariable will be available in our view.

-> $scope.toggle = function(modalstate, id) {...} displays the modal form

-> $scope.save = function(modalstate, id){...} saves a new record or updates an existing record depending on whether the variable id has a value or not.

-> $scope.confirmDelete = function(id){...} deletes an existing record


Step 7: Create a blade view

Now go to /resources/views and create a new file name index.blade.php and update the below code into your file:
index.blade.php

<!doctype html>
<html lang="en" ng-app="customerRecords">

<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 CRUD application Angular JS - meaningarticles.com</title>
</head>

<body>
    <div class="container" ng-controller="customersController">
        <header>
            <h2>customers Database</h2>
        </header>
        <div>
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Contact No</th>
                        <th>
                            <button id="btn-add" class="btn btn-primary
btn-xs" ng-click="toggle('add', 0)">Add New customer</button>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="customer in customers">
                        <td>{{ customer.id }}</td>
                        <td>{{ customer.name }}</td>
                        <td>{{ customer.email }}</td>
                        <td>{{ customer.contact_number }}</td>
                        <td>
                            <button class="btn btn-default btn-xs
btn-detail" ng-click="toggle('edit', customer.id)">Edit</button>
                            <button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(customer.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="frmcustomers" 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="Fullname" value="{{name}}" ng-model="customer.name" ng-required="true">
                                    <span class="help-inline" ng-show="frmcustomers.name.$invalid
&& frmcustomers.name.$touched">Name field is required</span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-12
control-label">Email</label>
                                <div class="col-sm-12">
                                    <input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}" ng-model="customer.email" ng-required="true">
                                    <span class="help-inline" ng-show="frmcustomers.email.$invalid
&& frmcustomers.email.$touched">Valid Email field is required</span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-12
control-label">Contact No</label>
                                <div class="col-sm-12">
                                    <input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}" ng-model="customer.contact_number" ng-required="true">
                                    <span class="help-inline" ng-show="frmcustomers.contact_number.$invalid
&&
frmcustomers.contact_number.$touched">Contact number 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="frmcustomers.$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/customers.js') ?>"></script>
</body>

</html>

Next, go to routes/web.php file and change welcome to index, like this:

web.php

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


Step 8: Start Development Server

We want to start the development server. Use the php artisan serve command and start your server:

php artisan serve

Now you may open bellow URL to your browser:

http://localhost:8000/

I hope it assists you, thanks for visiting my article if you like my article then share it with your friends on the social media platform.

Happy Coding.....