Thứ Ba, 6 tháng 12, 2016

Laravel 5 Tutorial : Laravel 5.3 Simple CRUD Application With Angular JS


Laravel 5.3 tutorial for beginners : Create simple Laravel 5.3 CRUD Operations with laravel 5.3 and Angular JS backend (REST API). At the previews lessons, we have create simple crud with laravel too, please read :
  1. Laravel 5.3 Crud Operation with Ajax
  2. Laravel 5.3 Crud Application with Resource Controller
  3. Laravel 5.3 Crud Opeartion with Vue.Js Full video
This lessons will use Laravel 5 for the backend and AngularJS for the front end. In accordance with the laws of beauty, we will use twitter bootstrap to add beauty to our simple application.

Video Tutorial Laravel CRUD with Angular Js


Create New Laravel Project

cd c:\server\htdocs\
....
composer create-project laravel/laravel laravelangularjs

Connect with Database (MySQL Database)

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelangularjs
DB_USERNAME=root
DB_PASSWORD=yourpasswqord

Create Migration and Tables

php artisan make:migration create_supplier_table

Create tables

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSupplierTable extends Migration {

    public function up(){
        // create supplier table
        Schema::create('supplier', function (Blueprint $table) {
         $table->increments('id');
         $table->string('supplierName')->unique();
         $table->string('supplierEmail')->unique();
         $table->string('supplierContact');
         $table->string('supplierPosition');
         $table->timestamps();
        });
    }

    public function down() {
        // Drop supplier table
        Scheme::drop('supplier');
    }
}

Run Migration

php artisan migrate

Create Model

php artisan make:model Supplier

Supplier.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Supplier extends Model{
    protected $table ='supplier';
    protected $fillable = array('id','supplierName','supplierEmail','supplierContact','supplierPosition');
}

Create Controller

php artisan make:controller SupplierController --resource

SupplierController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Supplier; // use our supplier model

class SupplierController extends Controller {

    public function index($id = null) {
      if ($id == null){
        return Supplier::orderBy('id', 'asc')->get();
      } else {
        return $this->show($id);
      }
    }

    public function store(Request $request) {
        $supplier = new Supplier;
        $supplier->supplierName = $request->input('supplierName');
        $supplier->supplierEmail = $request->input('supplierEmail');
        $supplier->supplierContact = $request->input('supplierContact');
        $supplier->supplierPosition = $request->input('supplierPosition');
        $supplier->save();
        return 'Supplier record successfully created with id' . $supplier->id;
    }
    public function show($id) {
        return Supplier::find($id);
    }
    public function update(Request $request, $id) {
        $supplier = Supplier::find($id);
        $supplier->supplierName = $request->input('supplierName');
        $supplier->supplierEmail = $request->input('supplierEmail');
        $supplier->supplierContact = $request->input('supplierContact');
        $supplier->supplierPosition = $request->input('supplierPosition');
        $supplier->save();
        return 'Supplier record successfully updated with id ' . $supplier->id;
    }
    public function destroy($id) {
        $supplier = Supplier::find($id)->delete();
        return 'Employee record successfully deleted';
    }
}

Create New Routes

Route::get('/', function () {
    return view('index');
});
Route::get('/api/supplier/{id?}', 'SupplierController@index');
Route::post('/api/supplier', 'SupplierController@store');
Route::post('/api/supplier/{id}', 'SupplierController@update');
Route::delete('/api/supplier/{id}', 'SupplierController@destroy');

Create New Views (index.blade.php)

<!DOCTYPE html>
<html lang="en" ng-app="getSupplier">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 5 and Angular CRUD Application</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>

    <div class="container">
      <h2>Simple CRUD Application with AngularJs</h2>
      <div ng-controller="SupplierController">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>Supplier Name</th>
              <th>Supplier Email</th>
              <th>Supplier Contact</th>
              <th>Supplier Position</th>
              <th>
                <button id="btn-add" class="btn btn-success btn-xs" ng-click="toggle('add', 0)">Add New Supplier</button>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="supplier in suppliers">
              <td>@{{ supplier.id }}</td>
              <td>@{{ supplier.supplierName }}</td>
              <td>@{{ supplier.supplierEmail }}</td>
              <td>@{{ supplier.supplierContact }}</td>
              <td>@{{ supplier.supplierPosition }}</td>
              <td>
                <button class="btn btn-warning btn-xs btn-detail" ng-click="toggle('edit', supplier.id)">
                  <span class="glyphicon glyphicon-edit"></span>
                </button>
                <button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(supplier.id)">
                  <span class="glyphicon glyphicon-trash"></span>
                </button>
              </td>
            </tr>
          </tbody>
        </table>
        <!-- show modal  -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">@{{form_title}}</h4>
              </div>
              <div class="modal-body">
                <form name="frmSupplier" class="form-horizontal" novalidate="">
                  <div class="form-group">
                    <label class="col-sm-3 control-label">Supplier Name</label>
                    <div class="col-sm-9">
                      <input type="text" class="form-control" id="supplierName" name="supplierName" placeholder="Supplier Name" value="@{{supplierName}}" ng-model="supplier.supplierName" ng-required="true">
                      <span ng-show="frmSupplier.supplierName.$invalid && frmSupplier.supplierName.$touched">Supplier Name field is required</span>
                    </div>
                  </div>

                    <div class="form-group">
                      <label class="col-sm-3 control-label">Supplier Email</label>
                      <div class="col-sm-9">
                        <input type="email" class="form-control" id="supplierEmail" name="supplierEmail" placeholder="Supplier Email" value="@{{supplierEmail}}" ng-model="supplier.supplierEmail" ng-required="true">
                        <span ng-show="frmSupplier.supplierEmail.$invalid && frmSupplier.supplierEmail.$touched">Supplier Email field is required</span>
                      </div>
                    </div>

                    <div class="form-group">
                      <label class="col-sm-3 control-label">Supplier Contact</label>
                      <div class="col-sm-9">
                        <input type="text" class="form-control" id="supplierContact" name="supplierContact" placeholder="Supplier Contact" value="@{{supplierContact}}" ng-model="supplier.supplierContact" ng-required="true">
                        <span ng-show="frmSupplier.supplierContact.$invalid && frmSupplier.supplierContact.$touched">Supplier Contact field is required</span>
                      </div>
                    </div>

                    <div class="form-group">
                      <label class="col-sm-3 control-label">Supplier Position</label>
                      <div class="col-sm-9">
                        <input type="text" class="form-control" id="supplierPosition" name="supplierPosition" placeholder="Supplier Position" value="@{{supplierPosition}}" ng-model="supplier.supplierPosition" ng-required="true">
                        <span ng-show="frmSupplier.supplierPosition.$invalid && frmSupplier.supplierPosition.$touched">Supplier Position field is required</span>
                      </div>
                    </div>
                </form>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmSupplier.$invalid">Save Changes</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <!-- Aangular Material load from CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.js"></script>

    <!-- Angular Application Scripts Load  -->
    <script src="{{ asset('angular/app.js') }}"></script>
    <script src="{{ asset('angular/controllers/SupplierController.js') }}"></script>
  </body>
</html>

AngularJS application structure

Laravel 5 Tutorial : Laravel 5.3 Simple CRUD Application With Angular JS

Create new folder (angular) in public\angular, and create new file (app.js) in there (public\angular\app.js)

public\angular\app.js

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

Create new folder (controller) in public\angular directory, and create new file (SupplierController.js) in public\angular\controller\SupplierController.js folder

public\angular\controller\SupplierController.js

app.controller('SupplierController', function($scope, $http, API_URL) {
  // retrieve Supplier listing from API
  $http.get(API_URL + "supplier")
  .success(function(response){
    $scope.suppliers = response;
  });

  // show modal Form
  $scope.toggle = function(modalstate, id) {
      $scope.modalstate = modalstate;
      switch(modalstate) {
        case 'add':
          $scope.form_title = "Add New Supplier";
          break;
        case 'edit':
          $scope.form_title = "Supplier Detail";
          $scope.id = id;
          $http.get(API_URL + 'supplier/' + id).success(function(response){
            console.log(response);
            $scope.supplier = response;
          });
          break;
        default:
          break;
      }
      console.log(id);
      $('#myModal').modal('show');
  }

  // save new supplier and update existing supplier
  $scope.save = function(modalstate, id) {
    var url = API_URL + "supplier";
    if (modalstate === 'edit') {
      url += "/" + id;
    }
    $http({
      method: 'POST',
      url: url,
      data: $.param($scope.supplier),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(response){
      console.log(response);
      location.reload();
    }).error(function(response){
      console.log(response);
      alert('This is embarassing. An error has occured. Please check the log for details');
    });
  }

 // delete supplier record
 $scope.confirmDelete = function(id) {
   var isConfirmDelete = confirm('Are you sure you want this record?');
   if (isConfirmDelete) {
     $http({
       method: 'DELETE',
       url: API_URL + 'supplier/' + id
     }).success(function(data){
       console.log(data);
       location.reload();
     }).error(function(data){
       console.log(data);
       alert('Unable to delete');
     });
   } else {
     return false;
   }
 }
});

Watch more Laravel videos

Laravel 5.3 CRUD with VueJS



Laravel 5.3 CRUD with AJAX


DOWNLOAD FULL SOURCE CODE Laravel 5.3 Simple CRUD Application With Angular JS HERE!!!.

See you next lessons ..

Không có nhận xét nào:

Đăng nhận xét