In this tutorial you will learn about the Laravel 7/6 Angular JS CRUD Example Tutorial and its application with practical example.
In this Laravel 7/6 Angular JS CRUD Example Tutorial I will show you how to create a simple AngularJS CRUD application with laravel. In this step by step tutorial, we will be creating a simple AngularJS SPA blog application with laravel. In this article, you will learn how to create fully functional CRUD (Create, Read, Update and Delete) REST API using laravel and integrate it with AngularJS Single Page Application.
Laravel 7/6 Angular JS CRUD Example Tutorial
You have to just follow this step by step angularJS crud application with laravel tutorial to create a fully functional angularjs crud application with laravel.
Laravel Angular JS CRUD Tutorial
Follow the below steps and create laravel angular web crud applications:
- 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 create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel lara-angular |
2). Setup Database Credentials in .env
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
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
Now we will create REST API controller using following artisan command:
1 |
php artisan make:controller API/CustomerController --api |
Now go to app/controller/API/CustomerController.php and put the following code in controller file:
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
<?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
In this step we will create a model file using following command:
1 |
php artisan make:model Customer |
Next, go to app/customer.php and update the below code into your file:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Customer extends Model { protected $fillable = [ 'id', 'name', 'email', 'contact_number' ]; } |
5). Define Route
Now, we will define the api route in routes/api.php file. So go to routes/api.php and update the below route into your file:
routes/api.php
1 |
Route::group(['prefix' => 'v1','namespace' => 'API'], function(){ Route::apiResource('customers', 'CustomerController'); }); |
6). AngularJS application structure
Now we will follow the following directory 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
We will first create app.js in /public/app directory, create a new file name app.js and put the following code in it:
1 2 |
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, go to /public/app/controllers folder and create a controller file customers.js. And put the following code in your customers.js file:
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
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; } } }); |
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:
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
<!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 && 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:
1 2 3 |
Route::get('/', function () { return view('index'); }); |
7). Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/ |