2017-03-10 103 views
-1

我正在爲我的api編寫更新方法。我需要更新請求的字段。 因此,我試圖只獲取請求的字段並更新它們。但是,即使您將$ fill填充到字符串,下面的代碼也會返回null。

 foreach ($fillableFields as $fill){ 
      $customerId->$fill = $request->get("$fill") ; 

編輯 - 1

我的代碼是像下面;

$fillableFields = array('lastname','firstname'); 

當我dd($ fill)它返回我null。

+0

你能告訴我們的'輸出$ fillableFields','$ customerId'和'$ request'請好嗎? –

+0

剛剛更新了我的問題 – Gvep

+0

以及如何定義$ customerId? –

回答

0

你的方法應該是。

public function yourMethod(Request $request) 
{ 
    try { 
     foreach ($fillableFields as $fill){ 
      $customerId->$fill = $request->get($fill) ; 
     } 

     } 

    } catch (\Exception $ex) { 

    } 
} 
+0

我試過了,仍然沒有奏效。它不會更新我的領域 – Gvep

0

laravel官方文檔提供了獲取請求參數的最佳方法,如下所示。

您可以根據您的具體需求獲取請求參數。

通過使用下面的陳述,你可以只獲得你只在屬性中指定的參數,例如:username,password。

$input = $request->only(['username', 'password']); 

如果您想獲取除特定字段以外的所有字段,您可以使用except參數定義下面的內容。例如:通過使用下面它將允許獲得除credit_card以外的所有字段。

$input = $request->except('credit_card'); 

有關請求參數的更多信息請參考官方文檔的網址:https://laravel.com/docs/5.4/requests

1

你忘了調用save()方法來更新你的對象:

foreach ($fillableFields as $fill){ 
     $customerId->$fill = $request->get($fill); 
     $customerId->save(); 
    } 
+0

非常感謝您的關注,這是因爲郵差和laravel。在postman中,我使用表單數據而不是x-www-form-urlencoded,所以當我切換時它運行良好。 – Gvep

+0

不客氣,很高興幫助! –