2017-04-07 28 views
0

我正在使用laravel 5.4,我試圖替換我的請求中的imagePath字段(重命名上傳的圖像)。laravel |如何替換表單請求中的字段?

解釋:

當表單提交請求場(request->imagePath)包含上傳的圖片的臨時位置,我認爲TMP圖像移動到一個目錄,而改變其名稱($name)。所以現在作爲request->imagePath仍然具有舊的tmp圖像位置我想要更改request->imagePath值以具有新的位置,然後創建用戶。

像這樣

 if($request->hasFile('imagePath')) 
    { 
      $file = Input::file('imagePath'); 

      $name = $request->name. '-'.$request->mobile_no.'.'.$file->getClientOriginalExtension(); 

      echo $name."<br>"; 

      //tried this didn't work 
      //$request->imagePath = $name; 

      $file->move(public_path().'/images/collectors', $name); 

      $request->merge(array('imagePath' => $name)); 

      echo $request->imagePath."<br>"; 
    } 

但它不能正常工作,這裏是輸出

mahela-7829899075.jpg 

C:\xampp\tmp\php286A.tmp 

請幫助

+0

只需使用它作爲一個規則陣列:'$請求[ '的ImagePath'] = $ name',沒有? –

+0

@ Jean-PhilippeMurray也嘗試過,但它仍然沒有改變任何東西 –

回答

2

我相信merge()是正確的方法,它會與提供的數組合並現有陣列在ParameterBag

但是,您正在錯誤地訪問輸入變量。嘗試使用$request->input('PARAMETER_NAME'),而不是...

因此,你的代碼應該是這樣的:

if ($request->hasFile('imagePath')) { 
    $file = Input::file('imagePath'); 
    $name = "{$request->input('name')}-{$request->input('mobile_no')}.{$file->getClientOriginalExtension()}"; 

    $file->move(public_path('/images/collectors'), $name); 
    $request->merge(['imagePath' => $name]); 

    echo $request->input('imagePath')."<br>"; 
} 

注意:您還可以通過你的路徑進入public_path(),它會串連它。

參考
檢索輸入:
https://laravel.com/docs/5.4/requests#retrieving-input
$request->merge()https://github.com/laravel/framework/blob/5.4/src/Illuminate/Http/Request.php#L269
public_pathhttps://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php#L635

+0

它印上了正確的名字!所以如果我做$ user = User :: create($ request-> all()); imagePath會在表中有新的值嗎? –

+0

是的,它會有新的價值。 '$ request-> input()'將返回所有輸入,'$ request-> all()'將返回所有輸入和文件。 – user1960364

+0

它工作!非常感謝!你保存了一天 –