Tự học Laravel: (18) FORM REQUEST

Last time I checked the input value of Form. This time, I will use the form request function to correct the input value check method.

CREATE FORM REQUEST

Use Artisan to generate a Form Request for Article.

php artisan make:request ArticleRequest

app/Http/Requests/ArticleRequest.php has been created.

<?php //app/Http/Requests/ArticleRequest.php
 
namespace App\Http\Requests;
 
use Illuminate\Foundation\Http\FormRequest;
 
class ArticleRequest extends FormRequest
{
    public function authorize()
    {
        return false;
    }
 
    public function rules()
    {
        return [
            //
        ];
    }
}

EDIT ARTICLEREQUEST.PHP

Edit the content for Article.

<?php
// ...
 
class ArticleRequest extends Request {
 
    public function authorize()
    {
        return true;  // ①
    }
 
    public function rules()
    {
        return [  // ②
            'title' => 'required|min:3',
            'body' => 'required',
            'published_at' => 'required|date',
        ];
    }
}
  1. The authorize method sets the authorization for the request. For example, if the currently logged-in user is not authorized, it returns false. For now, we will return true so that anyone can add Articles data.
  2. The rules method returns a validation rule.

CONTROLLER

Modify to use ArticleRequest in the store method of ArticlesController.php.

<?php
// app/Http/Controllers/ArticlesController.php
 
use App\Http\Requests\ArticleRequest;
 
// ...
 
class ArticlesController extends Controller {
 
    // ...
 
    public function store(ArticleRequest $request) {  // ①   
        Article::create($request->validated());
        return redirect('articles');
    }
}
  1. The class received by the store method has been changed from Illuminate\Http\Request to App\Http\Requests\ArticleRequest. This alone will eliminate the need for validate, which was previously done in the store method. ArticleRequest redirects to the previous screen when there is an error. The controller is slim and super cool.

As a precaution, whether the input check works as before or do not forget the operation check

Leave a Reply

Your email address will not be published.

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