隐式枚举绑定在Laravel的路线上的问题
我有这条路线
Route::get('/post/{post:uuid}', [\App\Http\Controllers\PostController::class, 'showPost']);
,它可以正常工作,如果用户输入一个没有uuID,则应用程序会响应404错误,但是现在我想通过在路由上使用枚举来添加更多条件。
我有一个名为 poststateenum.php
的枚举,
<?php
namespace Modules\Muse\Enum;
use App\Http\Traits\EnumTrait;
enum PostStateEnum: string
{
use EnumTrait;
case DRAFT = 'draft';
case WAITING_APPROVAL = 'waiting_approval';
case APPROVED = 'approved';
case REJECTED = 'rejected';
case PUBLISHED = 'published';
case UNPUBLISHED = 'unpublished';
}
我想在路由中添加条件:如果 $ post- post-&gt; state
is poststateenum ::已发布我想在我的
PostController
中转到“ showpost”
,目前,我在控制器上处理该逻辑
public function showPost(Post $post)
{
if ($post->state == PostStateEnum::PUBLISHED)
{
dump($post);
} else {
return abort(404);
}
}
我知道,我需要只有一个状态来从路线上验证这一点,/ruting#nimit-enum绑定“ rel =“ rel =” nofollow noreferrer”>那是对的吗?
可能吗?还是我的方式更好?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您在路线上会带来什么
枚举
。它不是关于已经保存的内容,而是将其用作过滤器 /输入。想象一下,您想拥有一条路线,该路线根据状态显示帖子。在您的控制器中,您将能够基于此过滤。
您的枚举不是来自输入,而是来自模型,因此您正在做的实际上是正确的侵犯。如果没有完成,请记住要投入枚举。
作为一个更一般的代码改进提示,如果您在示例中所做的像可读性不是最佳的事情,那么在这些情况下,您可以扭转IF逻辑并进行早期返回方法。
I think you are confusing what
enums
in the route can bring. It is not about what is already saved, but more to use it as a filter / input. Imagine you want to have a route, that show posts based on status.In your controller you would be able to filter based on that.
Your enum is not from the input, but from the model, therefor what you are doing is actually the correct aproach. If not done, remember to cast your enum.
As a more general code improvement tip, doing if else, like you did in your example is non optimal for readability, you can in these cases, reverse the if logic and do an early return approach.