Tuesday, May 23, 2017

How to upload image in laravel using AngularJs and store into databse?

Here is my Code Files that describe Form of new record Insert with file upload. here is also my controller file, model file and Angular model file and also javascript file. please help me to insert record with image in to database (mongo db). when i hide code of image upload then record added successfully in to database table but when i add file upload tag then it's not working. It shows "ReferenceError: response is not defined" Error

<!-- Index.php -->
<div class="container">
    <div  ng-controller="employeesController">
        <div class="row">
            <div class="col-sm-6"><h2>Employees Database</h2></div>
            <div class="col-sm-6"><input type="text"  value="Search" ng-model="searchquery"  class="form-control"  placeholder="Search" style="margin-top: 20px;margin-bottom: 10px;"></div>
        </div>
        <!-- Table-to-load-the-data Part -->
        <table class="table table-striped table-bordered table-hover">
            <thead class="thead-inverse">
                <tr>
                    <th>ID</th>
                    <!--<th width="10%">Photo</th>-->
                    <th>Name</th>
                    <th>Email</th>
                    <th>Contact No</th>
                    <th>Position</th>
                    <th><button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Employee</button></th>
                </tr>
            </thead>
            <tbody>            
                <!--<tr ng-repeat="employee in filtered = (employees | filter:searchquery) | startFrom:(currentPage-1)*maxSize | limitTo:maxSize">-->
                <tr ng-repeat="employee in employees.slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage)) | filter:searchquery">
                    <td></td>
                    <!--<td><img ng-if="employee.photo" class="img-circle" src="." height="50" width="50"></td>-->
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>
                        <!--<button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', employee._id)"><i class="fa fa-edit text-info"></i></button>
                        <button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(employee._id)">Delete</button>-->
                        <a ng-click="toggle('edit', employee._id)" tooltip-placement="top" uib-tooltip="Edit "><i class="fa fa-pencil text-info"></i></a>
                        <a ng-click="confirmDelete(employee._id)" tooltip-placement="top" uib-tooltip="Delete"><i class="fa fa-trash-o text-danger"></i></a>
                    </td>
                </tr>
            </tbody>
        </table>
        <!-- End of Table-to-load-the-data Part -->
        <div class="row">
            <div class="col-sm-6">View 
                <select ng-model="viewby" ng-change="setItemsPerPage(viewby)"><option>3</option><option>5</option><option>10</option></select> records at a time.
            </div>
            <div class="col-sm-6">
                <uib-pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" class="pagination-sm" items-per-page="itemsPerPage"></uib-pagination>
            </div>
        </div>
        <!-- Modal (Pop up when detail button clicked) -->
        <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"></h4>
                    </div>
                    <div class="modal-body">
                        <form name="frmEmployees" class="form-horizontal" novalidate="" enctype="multipart/form-data">

                            <div class="form-group error">
                                <label for="inputEmail3" class="col-sm-3 control-label">Name</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value=""
                                    ng-model="employee.name" ng-required="true">
                                    <span class="help-inline"
                                    ng-show="frmEmployees.name.$invalid && frmEmployees.name.$touched">Name field is required</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Email</label>
                                <div class="col-sm-9">
                                    <input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value=""
                                    ng-model="employee.email" ng-required="true">
                                    <span class="help-inline"
                                    ng-show="frmEmployees.email.$invalid && frmEmployees.email.$touched">Valid Email field is required</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Contact Number</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value=""
                                    ng-model="employee.contact_number" ng-required="true">
                                <span class="help-inline"
                                    ng-show="frmEmployees.contact_number.$invalid && frmEmployees.contact_number.$touched">Contact number field is required</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Position</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control" id="position" name="position" placeholder="Position" value=""
                                    ng-model="employee.position" ng-required="true">
                                <span class="help-inline"
                                    ng-show="frmEmployees.position.$invalid && frmEmployees.position.$touched">Position field is required</span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Photo</label>
                                <div class="col-sm-9">
                                    <input ng-model="employee.image" type="file" class="form-control" accept="image/*" onchange="angular.element(this).scope().uploadedFile(this)" >
                                    <img ng-src="" style="width:300px;">
                                </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="frmEmployees.$invalid">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>



<!-- employee.js -->
app.controller('employeesController', function($scope, $filter, $http, API_URL) {
    //retrieve employees listing from API
    $http.get(API_URL + "employees").then(successCallback, errorCallback);
    function successCallback(response){
        //success code      
        $scope.employees = response.data;
        $scope.viewby = '10';
        $scope.totalItems = response.data.length;
        //alert($scope.totalItems);
        $scope.currentPage = '1';
        $scope.itemsPerPage = $scope.viewby;
        $scope.maxSize = '10'; //Number of pager buttons to show
        $scope.setPage = function (pageNo) {
          $scope.currentPage = pageNo;
        };
        $scope.pageChanged = function() {
          console.log('Page changed to: ' + $scope.currentPage);
        };
        $scope.setItemsPerPage = function(num) {
          $scope.itemsPerPage = num;
          $scope.currentPage = 1; //reset to first page
        }

        $scope.noOfPages = Math.ceil($scope.employees.length/$scope.maxSize);
        //alert($scope.noOfPages);
        $scope.filter = function() {
            $timeout(function() { 
                $scope.noOfPages = Math.ceil($scope.filtered.length/$scope.maxSize);
            }, 10);
        };
    }
    function errorCallback(error){
        //error code
    }




    //show modal form
    $scope.toggle = function(modalstate, id) {
        $scope.modalstate = modalstate;

        switch (modalstate) {
            case 'add':
                $scope.form_title = "Add New Employee";
                break;
            case 'edit':
                $scope.form_title = "Employee Detail";
                $scope.id = id;
                $http.get(API_URL + 'employees/' + id).then(successCallback, errorCallback);
                        function successCallback(response){
                            //success code
                            console.log(response);
                            $scope.employee = response.data;
                        }
                        function errorCallback(error){
                            //error code
                        }
                break;
            default:
                break;
        }
        console.log(id);
        $('#myModal').modal('show');
    }
    //save new record / update existing record
    $scope.save = function(modalstate, id) {
        $scope.frmEmployees.image = $scope.files[0];
        var url = API_URL + "employees";
        //append employee id to the URL if the form is in edit mode
        if (modalstate === 'edit'){
            url += "/" + id;
            //alert(url);
        }
        $http({
            method: 'POST',
            url: url,
            transformRequest: function (data) {
                  var formData = new FormData();
                  formData.append("image", $scope.employee.image);  
                  //alert(formData);
                  return formData;  
              },  
            data: $.param($scope.employee),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })
        .then(success, error);
            function success(response){
                console.log(response);
                location.reload();
            }
            function error(error){
                console.log(response);
                alert('This is embarassing. An error has occured. Please check the log for details');
            }
    }


    $scope.uploadedFile = function(element) {
            $scope.currentFile = element.files[0];
            var reader = new FileReader();

            reader.onload = function(event) {
              $scope.image_source = event.target.result

              $scope.$apply(function($scope) {
                $scope.files = element.files;
              });
            }
                    reader.readAsDataURL(element.files[0]);
          }


    //delete record
    $scope.confirmDelete = function(id) {
        var isConfirmDelete = confirm('Are you sure you want this record?');
        if (isConfirmDelete) {
            $http({
                method: 'DELETE',
                url: API_URL + 'employees/' + id
            })
                    .then(success, error);
            function success(response){
                console.log(response);
                location.reload();

            }
            function error(error){
                console.log(response);
                alert('This is embarassing. An error has occured. Please check the log for details');
            }
        } else {
            return false;
        }
    }
});
/*app.filter('startFrom', function() {
    return function(input, start) {
      start = +start; //parse to int
      return input.slice(start);
    };
});*/


<!-- Employee.php Controller file-->
var app = angular.module('employeeRecords', ['ui.bootstrap']).constant('API_URL', 'http://localhost/blog/public/');


<!-- employee.js -->
<?php

namespace App\Http\Controllers;

use App\Employee;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;


class Employees extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index($id = null) {
        if ($id == null) {
            return Employee::orderBy('id', 'asc')->get();
        } else {
            return $this->show($id);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */


    public function store(Request $request) {
        $employee = new Employee;

        $employee->name = $request->input('name');
        $employee->email = $request->input('email');
        $employee->contact_number = $request->input('contact_number');
        $employee->position = $request->input('position');

        $employee->photo =$request->file('photo');
        $filename=$employee->getClientOriginaName();
        storage::put('uploads/'.$filename,file_get_contents($request->file('photo')->getRealPath()));
        $employee->image=$filename;

        $employee->photo = 'uploads/'. $request->input('photo');



        $employee->save();

        return 'Employee record successfully created with id ' . $employee->id;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
        return Employee::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id) {
        $employee = Employee::find($id);

        $employee->name = $request->input('name');
        $employee->email = $request->input('email');
        $employee->contact_number = $request->input('contact_number');
        $employee->position = $request->input('position');
        $employee->save();

        return "Sucess updating user #" . $employee->id;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */

     public function destroy(Request $request)
      {
        $employee = Employee::find($request->id);
        $employee->delete();

            return "Employee record successfully deleted #" . $request->id;
        }

} 

<!-- Employee.php Model File-->
<?php

namespace App;

//use Illuminate\Database\Eloquent\Model;
//use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Model as Eloquent;


class Employee extends Eloquent
{
   public $collection = 'employees';
   public $fillable = ['id', 'name', 'email','contact_number','position','photo'];
}



<!-- routes.php -->
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

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

Route::get('/employees/{id?}', 'Employees@index');
Route::post('/employees', 'Employees@store');
Route::post('/employees/{id}', 'Employees@update');
Route::delete('/employees/{id}', 'Employees@destroy');



via Hiren Karsadiya

Advertisement