Skip to content

Instantly share code, notes, and snippets.

@innocenzi
Last active September 7, 2022 11:58
Show Gist options
  • Save innocenzi/b5e676eb8fd24069e3251bc424765b36 to your computer and use it in GitHub Desktop.
Save innocenzi/b5e676eb8fd24069e3251bc424765b36 to your computer and use it in GitHub Desktop.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Tightenco\Ziggy\Ziggy;
class GenerateRoutesCommand extends Command
{
protected $signature = 'routes:generate';
protected $description = 'Generates the routes definitions for the front-end.';
public function handle()
{
if ($success = $this->writeRoutes()) {
$this->info("Routes written to <comment>{$this->getRoutesFilePath()}</comment>.");
}
return $success ? self::SUCCESS : self::FAILURE;
}
/**
* Gets the routes.
*/
protected function getRoutes(): array
{
return (new Ziggy())
->filter(['*debugbar.*', '*ignition.*'], false)
->toArray();
}
/**
* Gets the path to the route file.
*/
protected function getRoutesFilePath(): string
{
return str_replace('/', \DIRECTORY_SEPARATOR, resource_path('json/routes.json'));
}
/**
* Writes the routes to the file system.
*/
protected function writeRoutes(): bool
{
return (bool) File::put(
$this->getRoutesFilePath(),
json_encode($this->getRoutes()),
);
}
}
import getRoute from 'ziggy-js'
import { url, routes, defaults } from '../../json/routes.json'
/**
* Gets an URL for a web route.
*/
export function route<Routes extends typeof routes, RouteName extends keyof Routes>(
name: RouteName,
params?: (Routes[RouteName] extends { bindings: any } ? Partial<Record<keyof Routes[RouteName]['bindings'], any>> : {}) & Record<string, any>,
absolute: boolean = true,
) {
return getRoute(
name as any,
params as any,
absolute,
{ url, routes, defaults } as any,
).toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment