2
votes

I'm building a mock-up API using the Laravel resource controllers all works well until I try to override the default Laravel resource route when calling a get create but Laravel simply wont accept the overwrite. The documentation states the following:

If it becomes necessary to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource; otherwise, the routes defined by the resource method may unintentionally take precedence over your supplemental routes:

In my code I have the following:

routes.php

Route::group(['prefix' => 'api/v1', 'middleware' => 'cors'], function () {   
    Route::get('test/create', 'V1\Universal\TestController@create2');
    Route::resource('test', 'V1\Universal\TestController');
});

TestController.php

public function create2()
{
    return "create 2 override function";
}


public function create()
{        
    return "create default function";
}

When calling the API /api/v1/test/create its always firing the create() method rather than the create2() method. According to the Laravel documentation my custom additional route should take precedence as its defined before the resource.

Any Ideas?

1

1 Answers

1
votes

If you want to overrite resource routes, you want to try to add them after Route::resource. The quote from documentation tells about how to add routes to resource route, not about how to override them:

If it becomes necessary to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource; otherwise, the routes defined by the resource method may unintentionally take precedence over your supplemental routes

You may also use except argument:

Route::group(['prefix' => 'api/v1', 'middleware' => 'cors'], function () {   
    Route::get('test/create', 'V1\Universal\TestController@create2');
    Route::resource('test', 'V1\Universal\TestController', ['except' => ['create']]););
});

In this case Route::resource will not create create route.