gpt4 book ai didi

php - Laravel 嵌套路由模型绑定(bind)

转载 作者:可可西里 更新时间:2023-11-01 12:38:42 24 4
gpt4 key购买 nike

我正在使用 Laravel 开发用于移动应用程序的 API,并且在嵌套路由上遇到路由模型绑定(bind)问题。该应用程序将有一个独立的 sqlite 数据库,它将在网络可用时将客户端旅程与中央服务器同步。因此,应用程序中的 PK 不能用于访问中央服务器上的记录。每个用户都有一个唯一的用户名,该用户名将存储在中央服务器上的一个表中,该表包含以下列:

  • user_id
  • username

旅程表将包含以下列:

  • journey_id
  • user_id
  • user_journey_id

其中 user_journey_id 将是客户端设备上旅程记录的 PK。这个想法是客户端可以通过以下方式访问 api: http://example.com/api/client/UNIQUE_USERNAME/journey/1234从中央服务器检索旅程。

我有以下资源设置:

Route::resource('client','ClientController');
Route::resource('client.journey','JourneyController');

并为客户端成功设置路由模型绑定(bind)如下:

$router->bind('client', function($value, $route) {
return \App\Client::where('username', '=', $value)->firstOrFail();
});

我在设置嵌套模型绑定(bind)时遇到了一些麻烦,因为我需要客户端 username 结合 user_journey_id 来检索正确的旅程。有没有办法通过路由模型绑定(bind)来做到这一点?
或者这应该只在 Controller 中完成,比如:

public function show(Client $client, $user_journey_id)
{
... // have logic here to get the journey.

这就是我目前的做法,但路由模型绑定(bind)肯定会让它更容易一些。

最佳答案

在 Laravel 中当然可以将多个 URL 参数绑定(bind)到模型,嵌套路由模型绑定(bind)也是如此。

需要注意的是,您需要为这些特定路由单独指定路由,而不是像您在示例中使用的那样使用 Laravel 的资源 Controller 。

要注册具有多个模型绑定(bind)的路由,您需要执行以下操作:

路由定义:

Route::get('/api/client/{user}/journey/{journey}', [
'as' => 'client.journey',
'uses' => 'JourneyController@getJourney'
]);

绑定(bind)定义:

$router->bind('user', function($value, $route) {
return \App\Client::where('username', '=', $value)->firstOrFail();
});

$router->bind('journey', function($value, $route) {
return \App\Journey::where('user_journey_id', '=', $value)->firstOrFail();
});

然后您会发现两个模型都被解析并注入(inject)到 Controller 类中的操作方法中:

public function show(User $user, Journey $journey)
{
//do whatever you need to do here...

这种方法唯一真正的缺点是您必须手动定义路由,而不是使用 Laravel 方便的资源 Controller 。当然,您可以实现一些您自己的逻辑,使您更容易定义这些类型的路由。

关于php - Laravel 嵌套路由模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31582588/

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