Form Request Validation in Laravel 5.8

Tạo Form Request Validation in Laravel 5.8, thường trong các website ta hay dùng kiểm tra các bước nhập của người dùng qua form validation mà ta có thể dùng jquery để làm việc này, nhưng nay trong Laravel Framework có đã cung cấp tính năng này ta có thể sử dụng nó như sau:

# Installing Laravel 5.8

composer create-project --prefer-dist laravel/laravel blog "5.8.*"

# Create Migrations Post

php artisan make:migration create_posts_table --create=posts 

Bên trên mình tạo một table posts để lưu các trường dữ liệu, bạn mờ file vừa được tạo trong thư mục database/migrations mở file lên và chỉnh sửa lại như code bên dưới đây

Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    $table->string('keywords');
    $table->string('description');
    $table->string('slug');
    $table->string('image');
    $table->text('body');
    $table->timestamps();
});

# Create Form Request Validation

php artisan make:request FormPost

Khi ta chạy câu lệnh bên trên sẽ tạo cho ta một file FormPost nằm trong thư mục App\Http\Request, ta mở file lên và cài đặt các tham số cần dùng trong Form request Validation, ở đây mình cài đặt như sau:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FormPost extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|unique:posts|max:255',
            'keywords'=>'required',
            'description'=>'required',
            'image' => 'mimes:jpeg,jpg,png,gif|required|max:10000',
            'body' => 'required'
        ];
    }

    public function messages()
    {
        return [
            'title.required' => 'Title is required!',
            'keywords.required' => 'Keywords is required!',
            'description.required' => 'Description is required!',
            'image.required' => 'Image is required!',
            'body.required' =>'Body is required'
        ];
    }
}

# Create Model in Laravel 

php artisan make:model Post 

Ta được file model Post trong App\Post, ta chỉnh lại các trường trong table của ta cần dùng 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'title', 'keywords', 'description','slug','image','body'
    ];
}

# Create Template Blade in Laravel

Ta tạo file form-validation.blade.php nằm trong thư mục views/pages và cấu hình form của ta

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6">
        @if (session('success'))
            <div class="alert alert-success">
                {{ session('success') }}
            </div>
        @endif
            <form action="{{route('formpost.store')}}" method="post" enctype="multipart/form-data">
            @csrf
                <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" name="title" placeholder="Title" class="form-control"/>
                  @error('title')
                        <small class="form-text text-muted">{{ $message }}</small>
                    @enderror
                </div>
                <div class="form-group">
                    <label for="keywords">keywords</label>
                    <input type="text" name="keywords" placeholder="Keywords" class="form-control"/>
                    @error('keywords')
                        <small class="form-text text-muted">{{ $message }}</small>
                    @enderror
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <input type="text" name="description" placeholder="Description" class="form-control"/>
                    @error('description')
                        <small class="form-text text-muted">{{ $message }}</small>
                    @enderror
                </div>
                <div class="form-group">
                    <label for="image">Image</label>
                    <input type="file" name="image"/>
                    @error('image')
                        <small class="form-text text-muted">{{ $message }}</small>
                    @enderror
                </div>
                <div class="form-group">
                    <label for="body">Body</label>
                    <textarea name="body" cols="30" rows="10" class="form-control">
                    
                    </textarea>
                    @error('body')
                        <small class="form-text text-muted">{{ $message }}</small>
                    @enderror
                </div>
                <div class="form-group">
                    <input type="submit" class="btn btn-success" value="Submit" />
                    <input type="reset" class="btn btn-primary" value="Reset" />
                </div>

            </form> 
        </div>
    </div>
</div>
@endsection

Trong đoạn code bên ta xác nhận các trường trong table, nếu các trường đó không được nhập sẽ được hiện thông báo lỗi, mà ta đã cái đặt trong FormPost.php của ta 

# Create Controller in Laravel 

php artisan make:controller FormValidationController.php 

Ta tạo một file FormValidationController.php trong thư mục App\Http\Controller , trong file này ta cài đặt như sau

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\FormPost;
use App\Post;
class FormValidationController extends Controller
{
    public function index(){
        return View('pages.form-validation');
    }
    /**
     * Store
     */
    public function store(FormPost $request){
        $validated = $request->validated();
        $validated['slug']=str_slug($request->title);
       // dd($validated);
        Post::create($validated);
        return redirect('/form-validation')->with('success', 'Add Success!');

    }
}

Trong đoạn code bên trên ta use App\Http\Requests\FormPost; của ta vừa tạo vào FormValidationController.php 
Ta tiếp tục cài đặt hàm store, trong hàm này mình làm nó cũng đơn giản thôi, mình không có lưu hình tới thư mục, các bạn có thể làm điều đó, bạn xem lại bài viết: Multiple Image Upload using Ajax with Laravel 5.8 tích hợp tính năng di chuyển hình ảnh tới thư mục cần muốn dùng

# Config Route in Laravel 

Mở file web.php trong thư mục routes/web.php và chỉnh sửa lại như sau:

Route::prefix('form-validation')->group(function () {
    Route::get('/','FormValidationController@index')->name('formpost.index');
    Route::post('/post','FormValidationController@store')->name('formpost.store');
});

# Test Form Request Validation in Laravel 

php artisan serve

http://localhost:8000/form-valication

Form Request Validation in Laravel 5.8Form Request Validation in Laravel 5.8Form Request Validation in Laravel 5.8

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)