2016-07-28 31 views
0

我在files表中存儲filenames + their extensionsfilename列。我的問題是,自只有名稱存在於$request對象中,沒有對應的擴展名,我無法使用唯一驗證規則驗證文件名,而無需首先修改輸入數據。例如:Laravel中子字符串的唯一驗證

// . . . 
$this->validate($request, [ 
    // Suppose the name of uploaded file is 'file'. 
    // The below rule will NEVER fail, because in the 
    // database, similar file will be stored as 'file.txt', 
    // thus 'file' != 'file.txt' 
    'filename' => 'unique:files' 
]); 
// . . . 

有沒有辦法驗證文件名忽略它的後綴(擴展名)在數據庫中?

+0

在你的代碼中,你在文件名後面附加了一個擴展名? –

+0

@MarcoAurélioDeleu驗證通過後,我連接文件名和它的擴展名,並將它們存儲在數據庫中。這是相當有趣的一段代碼,是否真的需要在這裏發佈? –

+0

這取決於我可能有一個解決方案,但它依賴於你改變策略,這意味着停止附加後驗證擴展,並做它之前。 –

回答

1

你可以嘗試覆蓋你Request類的all()方法和驗證之前,而不是之後追加分機。這將是這樣的

public function all() { 
    $data = parent::all();   // Get all the data in your request 
    $data['filename'] .= '.txt'; // Concatenate the file extension 

    return $data;   // DONT FORGET TO RETURN THE CHANGED DATA 
} 

現在,您的規則將正常工作,因爲它會爲文件搜索與擴展。 提醒:你需要停止追加在您的控制器或任何你所使用的這樣的地方延伸,否則你會filename.txt.txt結束,將是回到原點1

就個人而言,我覺得它有些凌亂覆蓋all()方法,每當我喜歡它的感覺,所以我有以下特點

trait SanitizeRequest { 

    protected $sanitized = false; 

    public function all() { 
     return $this->sanitize(parent::all()); 
    } 

    protected function sanitize(array $inputs) { 
     if ($this->sanitized) return $inputs; 

     foreach ($inputs as $field => $value) { 
      if (method_exists($this, $field)) 
       $inputs[$field] = $this->$field($value); 
     } 
     $this->replace($inputs); 
     $this->sanitized = true; 
     return $inputs; 
    } 

} 

這個特點讓我寫與字段名稱自定義的方法,每當我想驗證之前清空它。使用這種方法可以讓你有這樣的方法

class YourRequest extends Request { 

    use SanitizeRequest; 

    /** 
    * Determine if the user is authorized to make this request. 
    * 
    * @return bool 
    */ 
    public function authorize() { 
     return true; 
    } 

    ... 

    protected function filename($value) { 
     return $value . '.txt'; 
    } 

} 
+0

你是MVP。謝謝你這樣一個整潔的解決方案! –