【问题标题】:Laravel - Passing parameter for patch requestLaravel - 为补丁请求传递参数
【发布时间】:2019-10-10 10:51:09
【问题描述】:

您好,我正在研究用于更新配置文件的更新方法,现在我正在通过将模型作为参数传递来更新配置文件,但我想传入配置文件的 id,因此路由是 patch('/profiles/podcast/{id}'' i我对 laravel 很陌生,所以我想知道在 laravel 中抓取对象时如何修改控制器和 phpunit 测试以更新这种方式?

控制器中的更新函数:

 public function update(PodcastProfile $podcastProfile)
{
    $this->user = Auth::user();
    $this->podcastProfile = $podcastProfile;

    if (!$this->hasPodcastProfile()) {
        abort(400, "You don't have a podcast profile configured");
    }

    $this->validation();

    $this->transaction();

    return $this->podcastProfile->toJson();
}

这是更新方法的当前路径

Route::patch('/profiles/podcast/{podcastProfile}', 'PodcastProfileController@update');

这是函数的phpunit测试用例

 /**
 * @test
 */
public function it_should_update_podcast_profile()
{
    $podcastDetails = $this->handlePostRequestToController();

    $this->json('patch', '/profiles/podcast/' . $podcastDetails['id'], $this->updateData)
        ->assertSuccessful();

    $this->checkPodcastProfile($this->updateData, $podcastDetails['id']);
    $this->checkGuestFormats($this->updateData['guest_format']);
    $this->checkAvailability($this->updateData['availability']);
    $this->checkEquipment($this->updateData['equipment']);
    $this->checkCategories($this->updateData['categories']);
    $this->checkLocation($this->updateData['country'], $this->updateData['city']);
}

【问题讨论】:

  • 我不太明白你的问题。目前您正在将PodcastProfileroute model bindingid 传递给路由,您只是想更改路由参数名称吗?
  • 是的,差不多
  • 然后您只需将您的路由更改为Route::patch('/profiles/podcast/{id}', ...),将控制器中的参数重命名为$id(并删除类型提示)并自己从database检索配置文件。
  • 好的,我不确定最好的方法我没有注意到路由模型绑定文档似乎是更好的选择,谢谢大家:D

标签: php laravel object phpunit


【解决方案1】:

嘿嘿,

如果我正确理解您的问题,您只需传递该配置文件的 ID,就像您说的那样:

Route::patch('/profiles/podcast/{podcastProfileId}','PodcastProfileController@update');

然后通过给定的 id 获取配置文件。

类似:

    $this->podcastProfile = App\PodcastProfile::find($podcastProfileId)

我也觉得选择像@Remul 描述的路由模型绑定方法会是更好的方法。

【讨论】:

  • 是的,我没有注意到文档中的路由模型绑定,它似乎确实是更好的选择,感谢您让我了解替代方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 2019-09-30
  • 1970-01-01
  • 2020-04-28
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多