How can I sanitize laravel 5.X Request input?

I have a class MyRequest.phpextending App\Http\Requests\Request. I want trim()every entry before verification, because the email with a space after it has not passed verification.

However has sanitize()been removed fromsrc/Illuminate/Foundation/Http/FormRequest.php

+4
source share
2 answers

I just stumbled upon the same problem.
I would like to show you another way to do this without extends, but with traits. (I'll take sample classes from Tarek Adam).

PHP Traits - , . , Trait - , extends do. , e.x. , , .

Laravel BaseController, .


\App\Traits\SanitizedRequest.php. , . .

namespace App\Trait;

trait SanitizedRequest{

    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;
    }
}


use SanitizedRequest.

namespace App\Http\Requests\Forms;

use App\Http\Requests\Request;
use App\Trait\SanitizedRequest; // Import the Trait 

class ContactRequest extends Request {
    use SanitizedRequest; // This line adds all the Trait functions to your current class

    public function authorize(){ return true; }
    public function rules(){ return []; }
}
+1
  • SanitizedRequest, Request.

  • YourRequest SanitizedRequest.

  • SanitizedRequest Request:: all() ...

    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;
        }
    }
    

CustomRequest, SanitizedRequest laravel.

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

Source: https://habr.com/ru/post/1624507/


All Articles