paulehenri-l/laravel-route-helpers

Rails 风格的路由助手,便于生成 Laravel 控制器的路径

2.0.0 2020-10-27 21:36 UTC

This package is auto-updated.

Last update: 2024-09-28 05:59:04 UTC


README

Build Status

路由助手是简单的函数,可以生成应用程序资源的路径。

例如,如果您有一个 PostsController,您将获得以下助手

  • posts_path()
  • post_path()
  • new_post_path()
  • edit_post_path()

这些可以在视图/app中使用,如下所示

<a href="{{ posts_path() }}">Posts</a>
<a href="{{ new_post_path() }}">Got to the post creation form</a>
<a href="{{ post_path($post) }}">Show the given post</a>
<a href="{{ edit_post_path($post) }}">Edit the given post</a>

<form method="POST" action="{{ posts_path() }}">
    <!-- Form to create a new post -->
</form>

<form method="POST" action="{{ post_path($post) }}">
    <!-- Form to edit the given post -->
</form>
redirect()->to(posts_path()); // Redirect to posts.index

最终目标是利用自动完成功能,快速创建资源路径,而不必记住确切的路由名称。

安装

您可以使用 composer 安装此软件包

composer require paulhenri-l/laravel-route-helpers

使用方法

像往常一样注册您的路由,但给它们命名。在下一个应用程序启动时,将生成和加载助手。

您的路由名称应该是 Laravel 使用的 7 个 RESTful 名称之一 (*.index, *.create, *.store, *.show, *.edit, *.update 和 *.destroy)

您的路由名称应仅包含字母数字字符、点和下划线,任何不符合此模式的路由都不会为其生成助手。

Route::resource('comments', 'CommentsController');

这将生成以下助手

comments_path();
comment_path();
create_comment_path();
edit_comment_path();

嵌套资源

如果您正在嵌套资源,生成的助手将保持嵌套。

Route::resource('posts.comments', 'PostsCommentsController');
post_comments_path();
post_comment_path();
create_post_comment_path();
edit_post_comment_path();

不规则名称

如果您为资源使用不规则名称,将使用正确的单数形式为助手。

Route::resource('people', 'PeopleController');
people_path();
person_path();
create_person_path();
edit_person_path();

如果此工具无法猜测您路由名称的正确单数形式,您将必须配置它: https://stackoverflow.com/questions/25646229/laravel-custom-inflection

单数资源

如果您有单数资源,则不能使用 index 函数,因为它会在复数和单数助手之间创建冲突。

Route::resource('account', 'AccountController')->except('index');

助手与路由函数类似

<?php

posts_path();
posts_path(['query' => 'param']);
posts_path(['query' => 'param'], true);
post_path($post);
post_comment_path([$post, $comment]);

手动编译助手文件

当您使用 local 环境运行应用程序时,助手文件将在您更改路由文件时重新编译。

在任何其他环境中,如果助手文件不存在,将在您应用程序的第一次启动时生成。

您还可以通过调用此 artisan 命令手动启动助手文件的生成。

php artisan route:compile-helpers

贡献

如果您对这个库的使用有任何疑问,请随时提出问题。

如果您认为文档或代码可以在任何方面得到改进,请提出 PR,我会很高兴地审阅它!