LoginSignup
0
0

More than 1 year has passed since last update.

[Laravel]フォームリクエストでバリデーション

Posted at

フォームリクエストを活用したバリデーションの仕方。
一度実装していたのに忘れていて時間食ったのでまとめときます。
自分用に書いてるところあるので雑だったらすみません。(笑)

Requestを作る

php artisan make:request PostRequest

PostRequestの中身

App/Http/Requests/PoseRequest
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest 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 [
            'user_id' => 'required|integer',
            'title' => 'required|string|max:30',
            'content' => 'string',
        ];
    }
}

authorizeのreturnがデフォルトではfalseになっていますが、trueに変えておきます。
ここがfalseのままだとコントローラーにリクエストが通りません。
rulesの部分にバリデーションルールを設定していきます。

PoseControllerの中身(storeアクション)

PostControllerからStoreを抜粋しました。

App/Http/Controllers/PostController
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;
use Auth;
use App\Http\Requests\ReviewRequest;

 〜省略〜

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(PostRequest $request)
    {
        $post = new Post();
        $post->fill($request->all())->save();
        return redirect()->route('post.show', ['post'=>$post]);
    }

use App\Http\Requests\ReviewRequest;の部分で先ほど作成したリクエストを読み込んでます。
storeアクションの引数にPostRequestを使用することでStoreアクション宛のリクエストがPostRequestを通ってくるので、そこでバリデーションが適応されます。

今回はデータの保存にfillを使用しているのでPostModelも編集しておきます。

PostModelの中身

App/Models/PostModel
〜省略〜

class Review extends Model
{
    use HasFactory;

    〜省略〜

    protected $fillable = [
        'user_id',
        'title',
        'comment',
  ];
}

fillableで指定した値のみがDBに保存することを許可します。
この設定をしないとfillを使用する場合はなにも保存できなくなるので。

以上でRequestを使用したバリデーションが使用できるはずです。

参考記事

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