PostsController
public function store(Request $request) { $this->validate($request, [ 'title'=> 'required', ]); Post::create($request->all()); return redirect('/posts'); }
Route
※古い書き方
Route::group(['middleware'=>'web', function(){ Route::resource('/posts', 'PostsController'); }]);
view: create
※古い書き方
@if(count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach($errors->all() as $error) <li>{{ @error }}</li> @endforeach </ul> </div> @endif
$ php artisan make:request CreatePostRequest
./app/Http/Request/CreatePostRequest.php
public function authorize() { return true; } public function rules() { return [ // 'title' => "required" ]; }
controller
public function store(CreatePostRequest $request) { $this->validate($request, [ 'title'=> 'required', ]); Post::create($request->all()); return redirect('/posts'); }
バリデーションは実務で日常的に使うので、比較的馴染みやすいように思います。