LoginSignup
0
0

More than 3 years have passed since last update.

Laravel6 独自のリクエストクラスを作成してpostしたらエラーが出た

Last updated at Posted at 2021-02-10

目的

  • Laravel6のアプリでバリデーションをリクエストクラスに記載するために独自のリクエストクラスを作成してデータをpostしたらエラーが出たので回避方法をまとめておく

環境

  • ハードウェア環境
項目 情報
OS macOS Catalina(10.15.5)
ハードウェア MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports)
プロセッサ 2 GHz クアッドコアIntel Core i5
メモリ 32 GB 3733 MHz LPDDR4
グラフィックス Intel Iris Plus Graphics 1536 MB
  • ソフトウェア環境
項目 情報 備考
PHP バージョン 7.4.11 Homebrewを用いてこちらの方法で導入→Mac HomebrewでPHPをインストールする
Laravel バージョン 6.X commposerを用いてこちらの方法で導入→Mac Laravelの環境構築を行う
MySQLバージョン 8.0.21 for osx10.15 on x86_64 Homwbrewを用いてこちらの方法で導入→Mac HomebrewでMySQLをインストールする

情報

  • 本エラーはAuthの認証機能を付与しているLaravelアプリだと発生するらしい。例にもれずエラーが出た筆者のアプリもAuthによる認証機能が付与されている。

経緯

  1. 下記コマンドを実行してリクエストクラスを作成した。

    $ php artisan make:request ContentRequest
    
  2. 作成されたリクエストクラスのファイルを下記のように記載した。

    アプリ名ディレクトリ/app/Http/Requests/ContentRequest.php
    <?php
    
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class ContentRequest extends FormRequest
    {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return false;
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            return [
                'content' => 'required',
            ];
        }
    }
    
  3. データがpostされるコントローラのメソッド(アクション)の引数にContentRequest $contentRequestを追加してデータをpostした。

エラー

  • 「403 This action is unauthorized.」というエラーが発生した。

    Forbidden.png

解決策

  1. 作成したリクエストクラスのauthorize()メソッド内部を下記のように書き換える。

    アプリ名ディレクトリ/app/Http/Requests/ContentRequest.php
    <?php
    
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class ContentRequest extends FormRequest
    {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            //下記を修正する
            return true;
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            return [
                'content' => 'required',
            ];
        }
    }
    
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