В статье разберем как экспортировать маршруты из Laravel в файл json для последующего использования в JS-приложении на Vue или React.
Решение заключается в том, чтобы после запуска команды php artisan route:json формировался json-файл со всеми маршрутами вашего Laravel приложения.
Вот такой результат мы ожидаем увидеть в файле routes.json:
{
"user.create": "user\/create",
"user.index": "user",
"user.store": "user",
"user.show": "user\/{id}",
"user.edit": "user\/{id}\/edit",
"user.update": "user\/{id}",
"user.destroy": "user\/{id}",
"home": "home"
// ...
}
Пошаговое руководство
Код взят из видео Front-end в фреймворке Laravel: как передать маршруты в скрипты JS
Введите команду php artisan make:command GenerateRoutesJson
В директории app/Console/Commands создался файл. Скопируйте в него нижеследующий код:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Routing\Router;
class GenerateRoutesJson extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'route:json';
protected $json_file_path = 'resources/js/routes.json';
protected $router;
/**
* The console command description.
*
* @var string
*/
protected $description = 'Export Laravel routes to JSON file';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(Router $router)
{
parent::__construct();
$this->router = $router;
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$routes = [];
foreach($this->router->getRoutes() as $route){
$routes[$route->getName()] = $route->uri();
}
File::put($this->json_file_path, json_encode($routes, JSON_PRETTY_PRINT));
echo "Routes exported to ".$this->json_file_path;
}
}
Создаем функцию для выборки маршрута в JS-пришложении
Создаем файл resources/js/route.js и копируем туда код:
var routes = require('./routes.json');
export default function(){
var args = Array.prototype.slice.call(arguments); // arguments - аргументы, переданные в функцию
var name = args.shift();
if(routes[name] === undefined){
console.log('Error: route "'+name+'" dosn't exist');
}else{
return '/' +
routes[name]
.split('/')
.map(function(str){
if(str[0] == '{'){
return args.shift();
}else{
return str;
}
})
.join('/');
}
}
Проверяем работу кода
В вашем app.js добавляем строчки:
import routes from './route';
console.log(routes('ROUTE_NAME')); // Маршрут без параметров
console.log(routes('ROUTE_NAME', [5])); // Маршрут с параметрами, например /user/{id}/edit
Комментарии (0)
Не писать ответ