Last active
January 27, 2016 20:32
-
-
Save bbatsche/93d802cd08f6e2841658 to your computer and use it in GitHub Desktop.
Angular 1.4 + Laravel 4.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"; | |
}]); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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