DEV Community

macarthurgonde
macarthurgonde

Posted on

Laravel Artisan command that automatically registers API routes based on your existing controllers.

  1. Create the Artisan Command
php artisan make:command GenerateApiRoutes

Enter fullscreen mode Exit fullscreen mode

This will create app/Console/Commands/GenerateApiRoutes.php.

  1. Implement the Command

Replace the content with:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class GenerateApiRoutes extends Command
{
    protected $signature = 'generate:api-routes';
    protected $description = 'Automatically create API endpoints based on Controllers';

    public function handle()
    {
        $controllerPath = app_path('Http/Controllers');
        $files = File::files($controllerPath);

        $routes = "";

        foreach ($files as $file) {
            $filename = $file->getFilenameWithoutExtension();
            if (Str::endsWith($filename, 'Controller')) {
                $resource = Str::kebab(str_replace('Controller', '', $filename));
                $routes .= "Route::apiResource('{$resource}', App\\Http\\Controllers\\{$filename}::class);\n";
            }
        }

        $apiRoutesFile = base_path('routes/api_generated.php');

        File::put($apiRoutesFile, "<?php\n\nuse Illuminate\Support\Facades\Route;\n\n" . $routes);

        $this->info("API routes generated in routes/api_generated.php");

        // Include this file in routes/api.php if not already included
        $apiFile = base_path('routes/api.php');
        $content = File::get($apiFile);
        if (!Str::contains($content, "api_generated.php")) {
            File::append($apiFile, "\nrequire __DIR__.'/api_generated.php';\n");
            $this->info("api_generated.php included in routes/api.php");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode
  1. How it Works

The command scans app/Http/Controllers for all controllers ending with Controller.

It creates an API resource route for each controller, following Laravel conventions.

Example: CustomerController → /api/customers

Writes all routes to routes/api_generated.php (so you don’t overwrite api.php).

Automatically includes api_generated.php in routes/api.php if not already included.

  1. Usage

After creating your controllers:

php artisan generate:api-routes

Enter fullscreen mode Exit fullscreen mode

Now your API endpoints are ready and live. You can check routes/api_generated.php:

Route::apiResource('customers', App\Http\Controllers\CustomerController::class);
Route::apiResource('orders', App\Http\Controllers\OrderController::class);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)