Search code examples
phplaravellaravel-5htmlpurifier

How to use Laravel 5 HTML Purifier on $request object?


I am using HTMLPurifier for Laravel 5 package for cleaning my input field. Currently my store() method is like this:

public function store(Request $request)
{
    // Some business logic goes here

    $post = Post::create($request->all());

    // More business logic
}

and my $request variable contains these:

{
  "_token": "zbyUnJuAbSliem40B6xjWJfGOayoFlRSVIvrDlDM",
  "title": "Test Title",
  "slug": "test-title",
  "category_id": "1",
  "tags": [
    "2"
  ],
  "body": "<p>Test body.</p>"
}

How can I use Purifier::clean() method on $request variable only to purify the $request->body element?

If I use Purifier::clean($request->all()) then it add <p> tag to all of the elements of $request object rather then only body element like this:

{
  "_token": "<p>zbyUnJuAbSliem40B6xjWJfGOayoFlRSVIvrDlDM</p>",
  "title": "<p>Test Title</p>",
  "slug": "<p>test-title</p>",
  "category_id": "<p>1</p>",
  "tags": [
    "<p>2</p>"
  ],
  "body": "<p>Test body.</p>"
}

Solution

  • OK I got the answer, it can be done by the following way:

    public function store(Request $request)
    {
        // Some business logic goes here
    
        $request->merge(['body' => Purifier::clean($request->get('body'))]);
        $post = Post::create($request->all());
    
        // More business logic
    }