sabunan
sabunan

Reputation: 637

API route prefix with a value of post data

Is it possible to have a dynamic API route prefix whose value is based on the organization field from post request data?

For instance, the post request data is:

id: 1, name: 'John Doe', organization: 'CISCO'

What I wanted in my route is:

Route::prefix('CISCO')->group(function() {
    Route::post('create', [Controller::class, 'create'];
})

And if it is not possible, is there any other way to pass the organization value so that I will be able to structure a dynamically prefixed route?

Upvotes: 1

Views: 1245

Answers (1)

Anthony Aslangul
Anthony Aslangul

Reputation: 3847

In your example, CISCO is a parameter in your URL.

You can do this:

Route::prefix('{organization}')->group(function() {
    Route::post('create', [Controller::class, 'create'];
});

Which leads to this route:

POST http://youdomain.com/CISCO/create

Then in your controller:

public function create($organization)
{
    dd($organization); //CISCO
}

Be careful with prefixes like this, since it can lead to routing problems. For instance, if you have another route like this:

Route::prefix('{organization}')->group(function() {
    Route::post('create', [Controller::class, 'create'];
});

Route::prefix('{shop}')->group(function() {
    Route::post('create', [ShopController::class, 'create'];
});

Laravel will have a hard time to understand which route it should use.

The good practice here is to add another prefix, so it looks like this:

Route::prefix('organization/{organization}')->group(function() {
    Route::post('create', [Controller::class, 'create'];
});

Route::prefix('shop/{shop}')->group(function() {
    Route::post('create', [ShopController::class, 'create'];
});

Also, keep in mind that using prefixes is useful when you have multiple routes using it. If you only have one route, you should only do something like this:


Route::post('organization/{organization}/create', [Controller::class, 'create'];
Route::post('shop/{shop}/create', [ShopController::class, 'create'];

Upvotes: 2

Related Questions