Question

In a Laravel 4.2 project, I have the following route:

Route::group(['prefix' => 'api/v' . Config::get('api.version')], function () {
    if (Input::get('api_key') != Config::get('api.key')) {
        App::abort(401, 'Invalid API key!');
    }

    // Do stuff below...
});

This is accessed by:

http://domain.com/api/v1/do-stuff/value1/value2?api_key=2fl2bkqg2yqlf2l872qa

This works great for users to access the API with their key. However, when I run php artisan migrate --seed it triggers that api_key restriction.

Is there a better way of restricting my route group by API key in Laravel that won't cause this issue with migrations?

Was it helpful?

Solution

When the route group is created, the API check is run instantly despite no route in the group being triggered. You can add the logic to a filter leaving the group to hold just the routes to avoid this and have the api check executed only when a route is filtered by it.

Route::filter("api", function()
{
    if (Input::get('api_key') != Config::get('api.key')) 
    {
        return App::abort(401, 'Invalid API key!');
    }
});

Then in your route group remove the inline code and add the filter

Route::group(array('prefix' => 'api/v1', 'before' => 'api'), function()
{
    // Routes here
});

As these are filters, they are disabled for unit tests. As the filter is only ever run when a route is executed in this group, artisan commands won't trigger the api check when the route group is created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top