Build a Basic CRUD App with Laravel and Angular

Laravel 6 angular js crud tutorial. In this tutorial, we would love to share with you how you can create a crud application in laravel 6 using the angular js.

Angular js

AngularJS is a powerful JavaScript client-side Model-View-Controller (MVC) framework. It is especially popular for building single page applications that behavior like AJAX application.

Laravel 6 Angular JS CRUD Tutorial

  • Install Fresh Laravel Setup
  • Setup Database Credentials in .env
  • 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

1). Install Fresh Laravel Setup

First of all, we need to install the laravel fresh application. Use the below command and download fresh new laravel setup :

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

2. Setup Database Credentials in .env

In this step, go to your project directory and open .env file and set your database credentials like this:

 DB_CONNECTION=mysql
 DB_HOST=127.0.0.1
 DB_PORT=3306
 DB_DATABASE=databasename
 DB_USERNAME=db_username
 DB_PASSWORD=db_password

3. Create REST API Controller

In this step, we need 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 creating a new CustomerController.

php artisan make:controller API/CustomerController --api

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

<?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);
    }
}

4. Create a Model

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

php artisan make:model Customer

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

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

5. Define Route

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

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

6). AngularJS application structure

Our application will have the following structure

laravel angular js application structure

Here :

  • 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 will 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 will be used to define our application

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/](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:

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

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:

<!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 6 Crud application Angular JS Tutorial</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
                                            &amp;&amp; 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
                                            &amp;&amp; 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
                                            &amp;&amp;
                                            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:

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

7. Start Development Server

We need to start the development server. Use the PHP artisan serve command and start your server :

 php artisan serve

Load the following URL in your web browser

http://localhost:8000/

#angular #Laravel #javascript

Build a Basic CRUD App with Laravel and Angular
7.70 GEEK