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.


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

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);  // ③
        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.


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

    <h1>Write a New Article</h1>
    @if ($errors->any())
        <div class="alert alert-danger">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
    {!! Form::open() !!}
    {!! Form::close() !!}


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


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.