更改Laravel路线参数 [英] Change Laravel route parameter

查看:80
本文介绍了更改Laravel路线参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在开发的平台中,可以通过向api/company/{id} API端点发送GET请求来请求用户的公司数据.

In the platform I'm developing it's possible to request the user's company data by sending a GET request to the api/company/{id} API endpoint.

默认情况下,id参数是整数,但通常也可以将其设置为字符串:api/company/mine将检索经过身份验证的用户的公司数据.

By default the id parameter is an integer but usually it's also possible to set it as a string: api/company/mine will retrieve the authenticated user's company data.

为此,我创建了一个中间件,该中间件拦截API调用,并将mine替换为实际的公司ID. 不幸的是,我的解决方案并不完全是我的初衷.

In order to allow this I created a middleware that intercepts the API call and replaces mine with the actual company ID. Unfortunately, my solution is not exactly what I had in mind.

这是我当前的解决方案:

Here's my current solution:

$request->merge([
    'id' => $request->user()->company
]);

这可以通过在请求的输入中添加id来实现,以便以后可以使用$request->input('id');对其进行访问,但是问题是,如果我尝试访问$request->route('id'),我仍然会获得旧值.

This works by adding the id to the request's input so that it can be accessed later on using $request->input('id');, but the problem is that if I try to access $request->route('id') I still get the old value.

是否可以直接更改route参数?

Is it possible to change the route parameter directly?

P.S.

我想到的另一种解决方案是使用新参数以编程方式实际创建一个新请求,然后将该请求传递给中间件中的next()函数.

Another solution that comes in my mind is to actually programmatically create a new request with the new parameter and then pass that one to the next() function in the middleware.

推荐答案

发现,在这种情况下,至少对我来说,最好的解决方案是在控制器操作中作为参数传递的请求中处理它模型存储库.

Found out that the best solution in this case, at least for me, was to deal with it in the request passed as a parameter in the controller action and in the model repositories.

创建新请求的问题在于,由于路由参数未更新,并且由于没有大量其他代码而无法手动更新路由参数,因此它只能部分工作.

The problem with creating a new request is that it's just partially working since the route parameters are not updated and it's not possible to update the route parameters manually without a lot of additional code.

另一种可能的解决方案是将请求重定向到正确的API端点或在控制器中处理.

Another possible solution is to redirect the request to the right API endpoint or deal with it in the controller.

这篇关于更改Laravel路线参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆