user4790312
user4790312

Reputation:

Laravel 5 disable and excluding CSRF for single route

i'm trying to exclude and disable CSRF for ajax request such as:

$('[id^="change_user_status_account-"]').click(function () {
    var id = $(this).attr('id').split('-');
    $.ajax({
        type: "POST",
        url: "{{ URL::route('changeUserStatusAccount') }}",
        data: {user_id: id[1]},
        success: function (data) {
        }
    });
    return false;
});

Exclude CSRF for changeUserStatusAccount route:

protected $except = [
    '/changeUserStatusAccount',
];

My Route:

Route::any('changeUserStatusAccount',  ['as'=>'changeUserStatusAccount','middleware' => 'csrf', function() {
        \DB::table('users')
            ->where('id', Request::input('user_id'))
            ->update(['status' => $info->status == 1 ? 0 : 1]);
        return 1;
}]);

i get Error 500 in firebug and thats not work correctly

Upvotes: 0

Views: 1032

Answers (2)

Carlos Arauz
Carlos Arauz

Reputation: 805

Just add the route in array $except inside app/Http/Middleware/VerifyCsrfToken.php, this work in Laravel 5.1

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'changeUserStatusAccount',
        'changeUserStatusAccount/*
    ];
}

From documentation: http://laravel.com/docs/5.1/routing#csrf-excluding-uris

Upvotes: 1

Noid
Noid

Reputation: 126

in your VerifyCsrfToken do this :

private $openRoutes = ['YOUR_OPEN_ROUTE/*'];

public function handle($request, Closure $next)
{

    foreach($this->openRoutes as $route) {

        if ($request->is($route)) {
            return $next($request);
        }
    }

    return parent::handle($request, $next);
}

Upvotes: 2

Related Questions