Tự học Laravel: (17) VALIDATION

Last time , I created a Form and added data to the Articles table, but I did not check the input data. This time, we will implement this input data check.

CONTROLLER

Modify the store method, which stores the data entered in the Form.

<?php
//app/Http/Controllers/ArticlesController.php
 
namespace AppHttpControllers;
 
use App\Article;
use App\Http\Controllers\Controller;
 
use Illuminate\Http\Request;  // ①'
 
class ArticlesController extends Controller {
 
    // ...
 
    public function store(Request $request) {  // ①
        $rules = [    // ②
            'title' => 'required|min:3',
            'body' => 'required',
            'published_at' => 'required|date',
        ];
        $validated = $this->validate($request, $rules);  // ③
 
        Article::create($validated);
 
        return redirect('articles');
    }
}
  1. We changed the acquisition method of the request. The last time I accessed the request using the \Request facade, this time I get an instance of the Illuminate\Http\ Request class from the arguments of the store method. Laravel’s controller writes a class with type hints in method arguments, and automatically generates an instance of that class and passes it. It’s very cool.
  2. Set the validation rule. Please refer to the official document for the details of validation rules. https://laravel.com/docs/master/validation#available-validation-rules
  3. I’m executing the controller’s validate() method.
  4. If there is an error here, it will automatically redirect you to the previous screen. This is cool again.

VIEW

Add an error display on the Form screen. 
Since multiple error messages are stored in $errors, @foreach is used to display the number.

//resources/views/articles/create.blade.php
 
@extends('layout')
 
@section('content')
    <h1>Write a New Article</h1>
 
    <hr/>
 
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
 
    {!! Form::open() !!}
        ...
    {!! Form::close() !!}
@endsection

OPERATION CHECK

Just in case, please input all items and make sure that the article is registered correctly.

SUMMARY

It is now possible to check input values ​​and display errors.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.