How can I sanitize laravel Request inputs?

Tarek Adam picture Tarek Adam · Jan 15, 2016 · Viewed 10.2k times · Source

I have MyRequest.php class extending App\Http\Requests\Request. I want to trim() every input before validation because an e-mail with a space after it does not pass validation.

However sanitize() was removed from src/Illuminate/Foundation/Http/FormRequest.php

Answer

Tarek Adam picture Tarek Adam · Jan 15, 2016
  1. Create an abstract SanitizedRequest class that extends the usual Request class.

  2. YourRequest class should extend your SanitizedRequest abstract class.

  3. Your SanitizedRequest class overrides Request::all() as like so...

    namespace App\Http\Requests\Forms;
    use App\Http\Requests\Request;
    
    abstract class SanitizedRequest extends Request{
    
        private $clean = false;
    
        public function all(){
            return $this->sanitize(parent::all());
        }
    
    
        protected function sanitize(Array $inputs){
            if($this->clean){ return $inputs; }
    
            foreach($inputs as $i => $item){
                $inputs[$i] = trim($item);
            }
    
            $this->replace($inputs);
            $this->clean = true;
            return $inputs;
        }
    }
    

Then a normal CustomRequest, but extend SanitizedRequest instead of laravel's Request class

    class ContactRequest extends SanitizedRequest{
        public function authorize(){ return true; }
        public function rules(){ return []; }
    }