0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

laravel formRequest バリデーションチェック前に実行されるメソッド

Posted at

概要

  • laravelのformRequestにて、バリデーションチェック前に実行されるprepareForValidation()メソッドをまとめる。

prepareForValidationメソッド

  • 使用用途はサニタイズ

  • つまり、「送られてきたリクエストの中身に悪意のあるHTML要素が含まれている場合カットする」などの処理をこちらに記載する。

  • 例えば下記のようにstrip_tags()関数を使って記載する。

    formRequest.php
    public function prepareForValidation()
    {
        $input = $this->all();
    
        // リクエストデータから悪意あるHTMLタグとPHPタグを取り除く
        $input['name'] = strip_tags($input['name']);
    
        // リクエストボディーがname要素だけの場合、HTMLタグを取り除いたキーと情報で置き換える
        $this->replace($input);
    }
    
  • あとは下記のようにstringで受け取った整数をintに変換するなどの処理も実施する事ができる。

    formRequest.php
    public function prepareForValidation()
    {
        $input = $this->all();
    
        // キーがidの値をint型に変換
        $input['id'] = (int) $input['id'];
    
        // リクエストボディーがid要素だけの場合、置き換えを行う
        $this->replace($input);
    }
    
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?