Skip to content

Instantly share code, notes, and snippets.

@Maxiviper117
Last active January 9, 2025 13:51
Show Gist options
  • Save Maxiviper117/c620f59d8b259e77b602302feacbe3cb to your computer and use it in GitHub Desktop.
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.
<?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];
}
}
@Maxiviper117
Copy link
Author

Maxiviper117 commented Jan 9, 2025

This Artisan command generates a routes.js file that maps Laravel's named routes to a structured JavaScript object. It also includes a route helper function to dynamically resolve routes with parameters.

How to Use:

  1. Add the GenerateRoutesJs command to your app/Console/Commands directory.

  2. Run the command:

    php artisan routes:generate-js

    This will create a resources/js/routes.js file.

  3. Import and use the generated file in your frontend code:

    import { routes, route } from './routes';
    
    // Access a route's URI directly
    console.log(routes['home'].uri); // Outputs: '/'
    
    // Generate a URL for a route with parameters
    console.log(route('post.show', { post: 42 })); // Outputs: '/posts/42'
  4. The route function:

    • Dynamically replaces parameter placeholders (e.g., {id}) in routes with actual values.
    • Throws an error if:
      • A route is not found.
      • Required parameters are missing.
    • Example:
      // Correct usage
      console.log(route('post.show', { post: 1 })); // Outputs: '/posts/1'
      
      // Error: Missing parameters
      console.log(route('post.show')); // Throws an error

Benefits:

  • Keeps frontend and backend route definitions in sync.
  • Simplifies working with Laravel's named routes, especially for SPAs.
  • Provides clear error messages for missing parameters or invalid routes.

This approach is ideal for modern JavaScript frameworks like Vue.js, React, or Svelte.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment