Summarize the basics of Laravel validation

Sep 4, 2020 PHP Laravel

Target

** Know the basics of Laravel validation and make it usable to some extent **

What is validation?

A function to display errors etc. for input contents such as forms. Even though it is a required form, if nothing is entered, an error message etc. can be displayed. Like this (↓)

image.png

Validation creation

Make a request

In the first place, validation is a function. Create a file that enables you to use the function with request.

Execute the following in the terminal to create a request file that enables validation.

 $ php artisan make: request ValidationRequest (filename you want to create)

When this command is executed, a request file with the file name entered in the terminal is created in (project name) \ app \ Http \ Requests.

Explain the request file

Such code is written in the created request file.

<? php

namespace App \ Http \ Requests;

use Illuminate \ Foundation \ Http \ FormRequest;

class ValidationRequest 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 [
            // //
        ];;
    }
}

As explained in the commented out part, the actual validation rules etc. are described in ** public function rules () **.

** public function authorize () ** is to determine whether the user who is currently operating the page is an authenticated user when the authentication function etc. is enabled. It is true by default and enabled, but if you don’t need it, leave it as false.

Create a validation rule

This time, let’s create a validation rule for the user search screen at the beginning. The file that sets the input contents confirmed by validation looks like this. The real file name is search.blade.php, but it looks like a .php file for good looks.

<div class = "card-header">
    User search
</ div>
<div class = "card-body">
<p> Enter the information of the user you want to search. </ p>
<div class = "search">
        <form method = "post" action = "result">
        <div class = "category">
        <p> Search items: </ p>
        <select name = "search_category">
        <option value = "0" selected> Please select </ option>
        @for ($ i = 0; $ i <4; $ i ++)
        <option value = "{{$ NAME [$ i]}}"> {{$ NAME [$ i]}} </ option>
        @endfor
</ select>
        </ div>
        <div class = "word">
        <p> Search word: </ p>
        <input type = "text" name = "search_word">
        </ div>
<input type = "submit" value = "search">
            @csrf
        </ form>
    </ div>

It’s not that important, so it’s enough to have a selector called serch_category and an input form called search_word and let result know that those values will be sent.

The following rules were created as validations in those forms.

public function authorize ()
{
    return true;
}

public function rules ()
{
    return [
        'search_category' =>'not_in: 0',
        'search_word' =>'required',
    ];;
}

Validate rules are specified in the form of ** 'validation rule' **, which is the name of the form to be validated'=>’. I will explain the rules established this time.

The rule that not_in: 0 of search_category should select a value other than value = '0'. The required of search_word is a required rule.

There are various other rules, but it is recommended to check the Official Document if necessary.

Apply validation rules

Now, let’s apply the rules we made. The application file of the request file that describes the validation rule is applied to the controller. And the controller to which it applies is not the controller of the page that inputs the value, but the controller of the page that receives or sends the input value **. Therefore, in this example, the validation rule is applied to the controller of the form submission destination, result.

<? php

namespace App \ Http \ Controllers;

use App \ Http \ Controllers \ Controller;
use Illuminate \ Http \ Request;
use App \ Http \ Requests \ SearchRequest;
use App \ User;

class ResultController extends Controller
{
    public function result (SearchRequest $ request)
    {
        $ category = $ request-> input ('search_category');
        $ word = $ request-> input ('search_word');
        $ search_data = array (
        'category' => $ category,
        'word' => $ word
        );
        $ user_data = User :: where ($ category,'like', "% $ word%")-> get ();
        return view ('user / result', ['Search' => $ search_data,'User' => $ user_data]);
    }
}

Even if it applies, declare the request created with ** use App \ Http \ Requests \ SearchRequest; ** and enter (SearchRequest $ request) in ** result (). ** Only. By doing this, SearchRequest works for the value sent before the processing ofresult ()is executed, and if the rule is not satisfied, the subsequent processing is not performed, and the previous screen and input You will be returned to the screen. When returning to the input screen, ** GET method redirects **, so be careful about routing processing.

Keep in mind that the controller to which the validation rule applies is the controller to which the data is sent **.

Show validation error

If you move the page as it is, nothing will be displayed and the screen will not change, so you need to tell that the validation rules are not met. To do this, modify the ~ .blade.php file as follows:


// Omitted
        <div class = "word">
        <p> Search word: </ p>
        <input type = "text" name = "search_word">
        </ div>
<input type = "submit" value = "search">
            @csrf
        </ form>
         @if (count ($ errors)> 0)
<ul class = "error">
@foreach ($ errors-> all () as $ error)
<li> {{$ error}} </ li>
@endforeach
</ ul>
@endif
    </ div>

If the validation rules are not met, error messages are stored in $ errors. If the validation rule is not met in this state, the following error will be displayed. image.png

I changed the error message to red in css, but now I can implement the validation function.

.error {
  color: red;
  font-size: 15px;
}

Validation customization### Customize error messages

You can now display an error message if the validation rules are not met, but the error message is in English. Not only do you want to speak Japanese, but you may also want to customize it to your liking. In such a case, enter the following code.


// Omitted

public function rules ()
{
    return [
        'search_category' =>'not_in: 0',
        'search_word' =>'required',
    ];;
}

public function messages () {
    return [
        'search_category.not_in'=>' Please enter a search category. ',
        'search_word.required' =>'Please enter the search word within 20 characters. ',
    ];;
}

Error messages can be customized with ** messages () **. The content is declared with ** name.validation rule to be validated => message you want to display **. This time, there is only one rule for both validation targets, so it looks like this, but if there are multiple rules, it can be declared as follows.

public function rules ()
{
    return [
        'entry_name' =>' required | max: 20 | unique: user, name',
    ];;
}

public function messages () {
    return [
        'entry_name.required' =>'Please enter a name. ',
        'entry_name.max' =>' Please enter the name within 20 characters. ',
        'entry_name.unique' =>' This name is already in use. ',
    ];;
}

Customize error message display location

In the photo above, the error messages were gathered in one place, but at the beginning, each error message was displayed for each item. If you want such a display, enter the code as follows.


// Omitted

<form method = "post" action = "result">
<div class = "category">
<p> Search items: </ p>
<select name = "search_category">
<option value = "0" selected> Please select </ option>
@for ($ i = 0; $ i <4; $ i ++)
<option value = "{{$ NAME [$ i]}}"> {{$ NAME [$ i]}} </ option>
@endfor
</ select>
</ div>
    
    @if ($ errors-> has ('search_category'))
    <div class = "error">
        <p> {{$ errors-> first ('search_category')}} </ p>
    </ div>
    @endif
.
    <div class = "word">
<p> Search word: </ p>
<input type = "text" name = "search_word">
</ div>
    
    @if ($ errors-> has ('search_word'))
    <div class = "error">
        <p> {{$ errors-> first ('search_word')}} </ p>
    </ div>
    @endif
.
    <input type = "submit" value = "search">
    @csrf
</ form>

I will explain the code that displays the error message. ** @if ($ errors-> has ('validation target name')) ** to determine if an error message is stored in $ errors for validation target name. If it seems to be stored, ** {{$ errors-> first ('validation target name')}} ** specifies to display the first error message in the target.

If you reflect the code so far in the file, you can use the validation function like the image at the beginning.

Make better use of validation

Hold input value

Even if a value that does not meet the validation rule is entered, I want to keep that value in the form etc. In such a case, set the following value in the form of the page for display.

<input type = "text" name = "name" value = "{{old ('name')}}">

By setting ** {{old ('validation target name')}} **, the value is retained even if the validation rule is not met.

Also, in the old function, the initial value can be specified by the second argument. In that case, it will be in the form ** {{old ('name to be validated', '0')}} **.

Make better use of validation

References