Last active
January 9, 2025 13:51
-
-
Save Maxiviper117/c620f59d8b259e77b602302feacbe3cb to your computer and use it in GitHub Desktop.
Laravel Artisan command to generate a JavaScript file with routes as structured objects for frontend use.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Facades\Route; | |
class GenerateRoutesJs extends Command | |
{ | |
protected $signature = 'routes:generate-js'; | |
protected $description = 'Generate a JavaScript file with all Laravel routes as an object, supporting parameters'; | |
public function handle() | |
{ | |
$routes = collect(Route::getRoutes())->filter(function ($route) { | |
return !is_null($route->getName()); // Only include named routes | |
})->mapWithKeys(function ($route) { | |
return [ | |
$route->getName() => [ | |
'uri' => $route->uri(), | |
'methods' => $route->methods(), | |
'parameters' => $this->extractParameters($route->uri()), | |
] | |
]; | |
})->toArray(); | |
$jsContent = 'const routes = ' . json_encode($routes, JSON_PRETTY_PRINT) . ';' . PHP_EOL; | |
$jsContent .= <<<EOT | |
function route(name, params = {}) { | |
if (!routes[name]) { | |
throw new Error('Route not found: ' + name); | |
} | |
let uri = routes[name].uri; | |
for (const [key, value] of Object.entries(params)) { | |
uri = uri.replace('{' + key + '}', value); | |
} | |
if (uri.includes('{')) { | |
throw new Error('Missing parameters for route: ' + name); | |
} | |
return uri; | |
} | |
export { routes, route }; | |
EOT; | |
$outputFile = resource_path('js/routes.js'); | |
file_put_contents($outputFile, $jsContent); | |
$this->info("JavaScript routes file generated at: {$outputFile}"); | |
return Command::SUCCESS; | |
} | |
protected function extractParameters($uri) | |
{ | |
preg_match_all('/{([^}]+)}/', $uri, $matches); | |
return $matches[1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Artisan command generates a
routes.js
file that maps Laravel's named routes to a structured JavaScript object. It also includes aroute
helper function to dynamically resolve routes with parameters.How to Use:
Add the
GenerateRoutesJs
command to yourapp/Console/Commands
directory.Run the command:
This will create a
resources/js/routes.js
file.Import and use the generated file in your frontend code:
The
route
function:{id}
) in routes with actual values.Benefits:
This approach is ideal for modern JavaScript frameworks like Vue.js, React, or Svelte.