CodeBriefly
Tech Magazine

Laravel Form Request Validations

5 9,690

Get real time updates directly on you device, subscribe now.

In this article, we will discuss how Laravel Form Request Validations works. I think, No need to describe the features of Laravel. Because we know very well.

To start further, Just remember we need a basic Laravel setup where we implement our example. Also, you have to read our previous article on Laravel Form Validationswhich provides help to understand the working of basic validations.

Laravel provides an option to create separate Form Request class where all the validation rules work.

You can use the given command to create a Laravel Form Request Class.

php artisan make:request PostRequest

After execution, an above command the request class is created at app/Http/Request directory. The Request directory automatically created after the command executes, if not available.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

The Request class contains two functions authorize and rules.

The authorize function return true, an exception will be thrown when rules failed.

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

The rules function to return the validation rules.

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'post_title'=>'bail|required|min:6',
        'post_content'=>'required'
    ];
}

Laravel provides lots of validation rules, you can check here the complete list.

Update Controller

Now, time to update our post controller.

// First we need to update the given statement at top of the class, but after the namespace declaration.
use App\Http\Requests\PostRequest;

// store function looks.
/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(PostRequest $request)
{
    $post = new Posts;
    $post->post_title = $request->post_title;
    $post->slug = str_slug($request->post_title);
    $post->post_content = $request->post_content;
    $post->save();

    return back();
}

After updating the controller, you can check your form submission. When you submit a form then validation exceptions thrown.

Laravel Form Request Validations

Change error placement

If you want show an error message with each element and apply some styles to differentiate the error messages. Then you have to apply some logic to handle the error message as per your requirement, as given bellow.

<h3>Add New Post</h3>
<form method="post" name="addpost" id="addpost" action="{{ url('/post') }}">
    {{ csrf_field() }}
    <div class="form-group">
        <label for="post_title">Title</label>
        <input type="text" class="form-control{{ $errors->has('post_title') ? ' is-invalid' : '' }}" id="post_title" name="post_title">
        @if ($errors->has('post_title'))
            <span class="invalid-feedback">
                <strong>{{ $errors->first('post_title') }}</strong>
            </span>
        @endif
    </div>
    <div class="form-group">
        <label for="post_content">Content</label>
        <textarea name="post_content" id="post_content" class="form-control{{ $errors->has('post_content') ? ' is-invalid' : '' }}"></textarea>
        @if ($errors->has('post_content'))
            <span class="invalid-feedback">
                <strong>{{ $errors->first('post_content') }}</strong>
            </span>
        @endif
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

After execution, the error messages looks like.

Laravel Form Request Validations

Custom Error Messages

If you want to update or customize the default error messages, then you need to add messages function in your Form Request Class.

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'post_title.required' => 'A post title is required',
        'post_content.required'  => 'A post content is required',
    ];
}

After updating the request class, then newly add  messages thrown on a failure.

Laravel Form Request Validations Custom Messages

Conclusion

In this article, I’m trying to explain you how Laravel Form Request Validations works. We will discuss more on validations in future article. Remember this to read out our previous article on Laravel Form Validations for better understanding. Please feel free to comments if any query.

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

5 Comments
  1. venky says

    I tried as you mention above. but after validations complete its redirect to same page , it’s not executes controller information for validations.

    1. venky says

      type error it’s not executes controller information after FormValidations.

  2. priya chugh says

    I have 12 controllers for handling different entities so do I need to make form request for each controller validation?

    1. Code Briefly says

      Yes, you have to make.

  3. Anton says

    But how to break validation next attributes after failure previous attributes?

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More