Skip to content
Advertisement

How can I sanitize laravel Request inputs?

I have MyRequest.php class extending AppHttpRequestsRequest. 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

Advertisement

Answer

I just came across for the same problem.
I’d like to show you another way of doing it without extends but with traits. ( I will take the Example Classes from Tarek Adam ).

PHP Traits are like functions which will be injected into the used class. The one main difference is that a Trait doesn’t need any dependency like a extends do. This means you can use a trait for more then just one class e.x. for Controllers, Requests and whatever you like.

Laravel provides some traits in the BaseController, we can do the same.


How to do it with a trait

Create a trait as file in AppTraitsSanitizedRequest.php. You can create it anywhere it doesn’t matter really. You have to provide the correct namespace for sure.

namespace AppTrait;

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


In your Request you can use the trait with use SanitizedRequest keyword.

namespace AppHttpRequestsForms;

use AppHttpRequestsRequest;
use AppTraitSanitizedRequest; // 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 []; }
}

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement