DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

Form Request Validation in Laravel 5.8

Firstly, we need install laravel 5.8

composer create-project --prefer-dist laravel/laravel blog "5.8.*"
Enter fullscreen mode Exit fullscreen mode

Continue! create file migrations in folder database/migrations table Post

php artisan make:migration create_posts_table --create=posts

Enter fullscreen mode Exit fullscreen mode

Open file create new in folder database/migrations, config the following code after

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();
});
Enter fullscreen mode Exit fullscreen mode

Create Form Request Validation

php artisan make:request FormPost
Enter fullscreen mode Exit fullscreen mode

You see file FormPost in folder App\Http\Request and you config the following code after

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'
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Create Model in Laravel

php artisan make:model Post 
Enter fullscreen mode Exit fullscreen mode
namespace App;

use Illuminate\Database\Eloquent\Model;

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

Create Template Blade in laravel

We need create file form-validation.blade.php in folder views/pages

@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>

Enter fullscreen mode Exit fullscreen mode

Create Controller in Laravel

php artisan make:controller FormValidationController.php 
Enter fullscreen mode Exit fullscreen mode

After when run command above, you to folder App\Http\Controller\ and open file create new, config the following code after

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!');

    }
}
Enter fullscreen mode Exit fullscreen mode

You need include FormPost to FormValidationController.php and use App\Post

Config Route in Laravel

You to folder Routes and open file web.php, add the following code after

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

Enter fullscreen mode Exit fullscreen mode

Test Form Request Validation in Laravel

php artisan server
Enter fullscreen mode Exit fullscreen mode

http://localhost:8000/form-validation

Post:Form Request Validation in Laravel 5.8

Top comments (0)