Posted by Arjun on Tuesday 7th April 2015

Form Validation in Laravel5: The Right Way

Laravel5 Laravel Form Request Class

Laravel 5.0 introduces Form Requests, which are a special type of class devoted to validating and authorizing form submissions. Each class contains at least a rules() method which returns an array of rules and an authorize() method which returns a true or false (Boolean) of whether or not the user is authorized to perform their request.

In this tutorial I am going to show you form validation with Form Request class.By using this technique we are validating data with out hitting the actual controller post method(Example:store()).

create routes :app/Http/routes.php

Route::get('/post/create', '[email protected]');
Route::post('/post/store', '[email protected]');

Create a controller - app/Http/controllers/PostController.php

Artisan command to generate post Controller, or else you can create post controller manually using any text editor.

php artisan make:controller PostController

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreatePostRequest; // import our create post request class

use Illuminate\Http\Request;


class PostController extends Controller {

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		return view('post.create');
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store(CreatePostRequest $request)
	{

	}


}

In the postController we have imported CreatePostRequest class with use App\Http\Requests\CreatePostRequest and we are using method injection technique(public function store(CreatePostRequest $request)) since we are using CreatePostRequest class only while creating new post. so we are injecting that into sore method.

Create view to show form - resources/views/post/create.blade.php

HTML to show the form.

@extends('app')

@section('content')
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Create Post</div>
                    <div class="panel-body">
                        @if (count($errors) > 0)
                            <div class="alert alert-danger">
                                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                                <ul>
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif

                        <form class="form-horizontal" role="form" method="POST" action="{{ url('/post/store') }}">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">

                            <div class="form-group">
                                <label class="col-md-4 control-label">Title</label>
                                <div class="col-md-6">
                                    <input type="text" class="form-control" name="title" value="{{ old('title') }}">
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-md-4 control-label">Content</label>
                                <div class="col-md-6">
                                    <textarea type="text" class="form-control" name="content"></textarea>
                                </div>
                            </div>


                            <div class="form-group">
                                <div class="col-md-6 col-md-offset-4">
                                    <button type="submit" class="btn btn-primary">Create post</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

Create FormRequest class - app/http/requests/CreatePostRequest.php

Artisan command to create form request class , or you can create manually.

php artisan make:request CreatePostRequest

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;


class CreatePostRequest extends Request {

    /**
     * The URI to redirect to if validation fails
     *
     * @var string
     */
    //protected $redirect = 'post/create';

    /**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
        // Only allow logged in users
        // return \Auth::check();
        // Allows all users in
        // you can apply other logic also
        // $this->route->parameter('id'); Here id is the route parameter EX: Route::get('post/view/{id}','[email protected]');
		return true;
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
        return [
            'title' => 'required',
            'content' => 'required'
        ];
    }

}

Now go to your browser and access web page by pointing to http://localhost/pubilc/post/create, you will get form. Submit it with out filling information ,you will get error messages. See the demo.

That is it. I hope you find this post useful. If you have questions or want to share your own advice, leave a comment!