Send csrf token using angularjs in laravel

Rakesh Sharma      No Comments  

Post form data and post csrf token using angularjs in laravel

Sometimes we need to use angularjs in our form to validate or posting data in laravel. there is also need of csrf token match. if we are not using html class form::open() then csrf token will not be automatically added to our form. so we need to manually send csrf token using angularjs in laravel.

How to send csrf token using angularjs in laravel :-

For this we need to define a constant then get value of csrf constant and send via http post

1. define angularjs app :-


var app = angular.module('myValidateApp', []);

2. define constant :-


app.constant("CSRF_TOKEN", '{!! csrf_token() !!}');

3. send via http post :-


app.controller('validateCtrl', function($scope, $http, CSRF_TOKEN) {
  $scope.submitForm = function(isValid) {
  // check all goes fine?
  if (isValid) {
    var data = {'_token':CSRF_TOKEN};
    $http({
            method: 'POST',
            url: 'YOUR_POST_URL',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
            data: $.param(data)
    }).
    success(function(data, status, headers, config) {
      alert(data);
    });
  }
};
});

How to Post Form data using angularjs in laravel :-

Below we will see an example of form that posting form data with csrf token using angularjs in laravel. so let’s create a angularjs and html form.

Send csrf token using angularjs in laravel

view:- create a “angpost.blade.php” under “resources/views/” and add below code


<form ng-app="myValidateApp" ng-controller="validateCtrl" name="myTestForm" ng-submit="submitForm(myTestForm.$valid)" novalidate>
<p>Username:<br />
<input type="text" name="username" ng-model="username" ng-model-options="{ updateOn: 'blur' }" required><br />
<span style="color:red" ng-show="myTestForm.username.$dirty && myTestForm.username.$invalid">
<span ng-show="myTestForm.username.$error.required">Username is required.</span>
</span>
</p>

<p>Phone:<br />
<input type="text" name="phone" ng-model="phone" ng-minlength="10" ng-model-options="{ updateOn: 'blur' }" ng-pattern="/^[0-9]+$/" required><br />
<span style="color:red" ng-show="myTestForm.phone.$dirty && myTestForm.phone.$invalid">
<span ng-show="myTestForm.phone.$error.required">Phone is required.</span>
<span ng-show="myTestForm.phone.$error.pattern">Phone must be numeric.</span>
<span ng-show="myTestForm.phone.$error.minlength">Phone must be min 10 char.</span>
</span>
</p>

<p>Email:<br />
<input type="email" name="email" ng-model="email" ng-model-options="{ updateOn: 'blur' }" required><br />
<span style="color:red" ng-show="myTestForm.email.$dirty && myTestForm.email.$invalid">
<span ng-show="myTestForm.email.$error.required">Email is required.</span>
<span ng-show="myTestForm.email.$error.email">Invalid email address.</span>
</span>
</p>

<p>
<input type="submit" value="Submit" ng-disabled="myTestForm.phone.$dirty && myTestForm.phone.$invalid || myTestForm.username.$dirty && myTestForm.username.$invalid || myTestForm.email.$dirty && myTestForm.email.$invalid">
</p>
</form>

controller :- create a “AngcsrfController.php” under “app/Http/Controllers” and add below code


<?php namespace App\Http\Controllers;
use Input;
use Validator;
use Redirect;
use Session;
class AngcsrfController extends Controller {

  public function angpost() {
    // Getting all post data
    if(Session::token() == Input::get('_token')){
      $data = Input::all();
      print_r($data);die;
    }
  }
}

Adding angularjs script :- include angularjs library file in your header or in the same view file.


<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

Now add the angularjs post script code in the same view file or footer


<script>
var app = angular.module('myValidateApp', []);
//Define csrf token as a constant.
app.constant("CSRF_TOKEN", '{!! csrf_token() !!}');
// pass token to controller function.
app.controller('validateCtrl', function($scope, $http, CSRF_TOKEN) {
  $scope.submitForm = function(isValid) {
  // check all goes fine?
  if (isValid) {
    var data = { 'username': $scope.username, 'email': $scope.email, 'phone': $scope.phone, '_token':CSRF_TOKEN};
    $http({
            method: 'POST',
            url: 'angcsrf/angpost',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
            data: $.param(data)
    }).
    success(function(data, status, headers, config) {
      alert(data);
    });
  }
};
});
</script>

Routes :- add below code in your "app/Http/routes.php"


Route::get('angpost', function() {
  return View::make('angpost');
});
Route::post('angcsrf/angpost', 'AngcsrfController@angpost');

After set all code run the url "yoursite/angpost" and fill the form and click on submit you will get a alert with success posted data with csrf token match. co you are done with send csrf token using angularjs in laravel and how to post form data using angularjs in laravel.