gpt4 book ai didi

php - Laravel:从请求中检索绑定(bind)模型

转载 作者:IT王子 更新时间:2023-10-28 23:45:17 25 4
gpt4 key购买 nike

有什么简单的方法可以在请求中检索路由绑定(bind)模型吗?

我想更新模型,但在此之前,我想使用 Requests authorize() 方法执行一些权限检查。但我只希望模型的所有者能够更新它。

在 Controller 中,我会简单地做这样的事情:

public function update(Request $request, Booking $booking)
{
if($booking->owner->user_id === Auth::user()->user_id)
{
// Continue to update
}
}

但我希望在请求中而不是在 Controller 中执行此操作。如果我这样做:

dd(Illuminate\Http\Request::all());

它只给我标量形式的属性(例如_method 等等,但不是模型)。

问题

如果我将模型绑定(bind)到路由,我如何从请求中检索该模型?

非常感谢。

最佳答案

绝对!这是我什至自己使用的方法。

你可以在请求中获取当前路由,然后是任意参数,像这样:

class UpdateRequest extends Request
{
public function authorize()
{
// Get bound Booking model from route
$booking = $this->route('booking');

// Check owner is the currently authenticated user
return $booking->owner->is($this->user());
}
}

不同于 smartman的(现已删除)答案,如果您已经通过路由模型绑定(bind)检索到模型,则不会引发另一个查找查询。

不过,我个人也会使用 policy在这里而不是在表单请求中进行授权检查。

关于php - Laravel:从请求中检索绑定(bind)模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29775032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com