Skip to content

Instantly share code, notes, and snippets.

@bbatsche
Last active January 27, 2016 20:32
Show Gist options
  • Save bbatsche/93d802cd08f6e2841658 to your computer and use it in GitHub Desktop.
Save bbatsche/93d802cd08f6e2841658 to your computer and use it in GitHub Desktop.
Angular 1.4 + Laravel 4.2
<?php
// app/filters.php
// ...
// Modify csrf filter to check tokens passed in HTTP headers
Route::filter('csrf', function()
{
$token = Request::ajax() ? Request::header('X-Csrf-Token') : Input::get('_token');
if (Session::token() !== $token) {
throw new Illuminate\Session\TokenMismatchException;
}
});
<!-- app/views/layouts/master.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add CSRF Token as a meta tag in your head -->
<meta name="csrf-token" content="{{{ csrf_token() }}}">
<!-- ... -->
</head>
<!-- ... -->
</html>
// public/js/moduleName.js
(function() {
"use strict";
// This should be the actual name of your module
var app = angular.module("moduleName", []);
// Find the token value from the page using jQuery
var token = $("meta[name=csrf-token]").attr("content");
// Set the token as an Angular constant
app.constant("CSRF_TOKEN", token);
// Configure $http to include both your token and a flag indicating the request is AJAX
app.config(["$httpProvider", "CSRF_TOKEN", function($httpProvider, CSRF_TOKEN) {
$httpProvider.defaults.headers.common["X-Csrf-Token"] = CSRF_TOKEN;
$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
}]);
})();
<?php
// app/controllers/PostsController.php
class PostsController extends \BaseController
{
// ...
public function destroy($id)
{
// ...
// Modify destroy() to send back JSON if it's been requested
if (Request::wantsJson()) {
return Response::json(array(/* ... */));
} else {
return Redirect::action('PostsController@index');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment