Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jvezina's avatar

How to create custom route controller resource

when creating a set of crud routes, laravel gives us the resource controller to use so a single line in routes/web.php takes care of create/show/update/etc.

In my app I have a bunch of different sets of csv data that need to get uploaded. It has a set of routes that handle uploading files, validation, processing, listing, etc - there's seven of them. That means for each upload, I have 7 lines in the routes/web.php file.

What I'd like to do is create something like the resource controller so I only have to add a single line in routes/web.php for each type of data upload.

Is that possible? How would I do that?

thanks,

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, it is possible to create a custom route controller resource in Laravel. You can achieve this by creating a custom route macro.

Here's an example of how you can create a custom route macro for handling data uploads:

// In your routes/web.php file

// Define the custom route macro
Route::macro('dataUpload', function ($uri, $controller) {
    Route::post($uri, $controller.'@store')->name($uri.'.store');
    Route::get($uri, $controller.'@index')->name($uri.'.index');
    Route::get($uri.'/create', $controller.'@create')->name($uri.'.create');
    Route::get($uri.'/{id}', $controller.'@show')->name($uri.'.show');
    Route::get($uri.'/{id}/edit', $controller.'@edit')->name($uri.'.edit');
    Route::put($uri.'/{id}', $controller.'@update')->name($uri.'.update');
    Route::delete($uri.'/{id}', $controller.'@destroy')->name($uri.'.destroy');
});

// Usage
Route::dataUpload('csv', 'CsvController');

In the above example, we define a custom route macro called dataUpload. This macro takes two parameters: the URI prefix and the controller name. It then creates the necessary routes for handling data uploads, similar to the resource controller.

You can use the dataUpload macro by calling it with the desired URI prefix and the name of your controller. In this case, we're using 'csv' as the URI prefix and 'CsvController' as the controller name.

This will generate the following routes:

POST /csv
GET /csv
GET /csv/create
GET /csv/{id}
GET /csv/{id}/edit
PUT /csv/{id}
DELETE /csv/{id}

You can modify the macro to fit your specific requirements, such as adding additional routes or changing the HTTP methods.

I hope this helps! Let me know if you have any further questions.

Please or to participate in this conversation.