5

In my application I want to disable CSRF when running on my laptop APP_ENV=local and on development too APP_ENV=dev. Can't get my head throguh how to do it in either routes.php or the web middleware. here's my routes.php

Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    })->middleware('guest');

    Route::group(['middleware' => 'auth'], function()
    {
        Route::resource('battles', 'BattlesController'); //, ['except' => ['index']]);
        Route::resource('disputes', 'DisputesController');
        Route::resource('messages', 'MessagesController');
    });

});

I could use some env file loading magic to ensure the app loads either of .local.ev, .dev.env, .test.env, .production.env but I still have to find a way to ensure that the web middleware includes CSRF only when not in local or dev

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
Anadi Misra
  • 1,925
  • 4
  • 39
  • 68

2 Answers2

10

The easiest way will be to disable the CSRF check directly in the middleware. In order to do that you'll need to modify App\Http\Middleware\VerifyCsrfToken class. Add there the following handle() method:

public function handle($request, \Closure $next)
{
    if (in_array(env('APP_ENV'), ['local', 'dev'])) {
        return $next($request);
    }

    return parent::handle($request, $next);
}
jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
  • looks like a good idea but it gives a parse error on the line `if (in_array(env('APP_ENV'), ['local', 'dev']) { ` – Anadi Misra May 14 '16 at 12:16
  • in 5.6 you don't seem to need this any more. I don't know how they fixed, or where as there seems to be no app env hacking, but they did – MrMesees Aug 16 '18 at 19:51
  • 1
    Just a heads up for anyone else. You should never call `env()` from within your Laravel app, except inside config files which are cached. Instead call `app()->environment()` to get the environment. – Trevor Gehman Nov 08 '19 at 03:44
1

I had similar trouble with testing environment which could be resolved by turning off middleware:

class ExampleTest extends TestCase {
    use WithoutMiddleware;
    ...
boroboris
  • 1,548
  • 1
  • 19
  • 32