【问题标题】:Laravel Postman crud use id in urlLaravel Postman crud 在 url 中使用 id
【发布时间】:2019-12-18 10:22:25
【问题描述】:

所以我在 laravel 中为客户制作了一个 crud API 并想在 postman 中对其进行测试,但我有一个问题/疑问。 我试图在 api 中找到客户端的 id,但找不到,我不知道为什么。 我想在邮递员 url 中给出 id。

在 api 路由中,我有这样的 $id:

Route::match(['get', 'post'], "/clients/{id?}", "ApiV2Controller@clients");

在clients函数中:

public function clients(Request $request, $id = null){

if($id){
        $client = Client::find($id);
        if(is_null($client)){
            return $this->sendError("404", 'client not found');
        }
    }
    else{
        $client = new Client;  
    }

    $client->clt_name = $request->name; 
    $client->clt_adress = $request->adress;
    $client->save();
}

邮递员网址:

localhost:8000/api/v2/clients/19?name=TestName&adress=TestAdress

上面写着client not found。

提前致谢!

【问题讨论】:

  • 你能把整个客户端函数粘贴到这里吗?你的数据库里有没有 id 19 的客户端?
  • 编辑了帖子,没有id = 19的客户
  • 如果没有 id = 19 的客户端,则输出正确。那有什么问题呢?
  • 它应该创造一个新的记录,但它没有。不确定我是否设置了正确的邮递员网址。
  • 不,您没有考虑 id 不为 null 并且该 id 未存储在您的数据库中的情况。

标签: laravel api postman


【解决方案1】:

您的代码没有错误。如果您的数据库中没有有效的 client_id,我认为您想创建客户端。这是解决方案:

public function clients(Request $request, $id = null)
{
    try{
        $client = Client::findOrFail($id);
    }
    catch(\Exception $e){
        $client = new Client;
    }
    $client->clt_name = $request->name; 
    $client->clt_adress = $request->adress;
    $client->save();
}

【讨论】:

  • 范围错误,$client 只存在于你的 try-catch 块中,不存在之后。
  • PHP 中的变量范围是函数,而不是块。因此,您可以在 try 块内分配一个变量,并在外部访问它,只要它们在同一个函数中。 stackoverflow.com/questions/32488313/…
猜你喜欢
  • 2018-09-12
  • 2020-04-04
  • 2020-02-28
  • 2021-10-29
  • 2021-01-18
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
相关资源
最近更新 更多