Share, Read & Learn

Laravel Form Validations

0 1,835

In this article, we will discuss how Laravel Form Validations work. As we know, Laravel provides lots of features to reduce the repetitive task. Laravel provides an easy way to apply server side validations.

Prerequisite, we need a working Laravel basic application where we test our new code. If you are new to Laravel then you can start from given articles.

Create Post Controller, Model, and Migration

You can use the given artisan command to create a new Post Controller.

php artisan make:controller PostController --resource

In the above mention command, we use “–resource”, means our controller contains all the basic function.

You can use the given command to create a new Post Model with migration.

php artisan make:model Post -m

In the above mention command, we use “-m”, means our migration file is created automatically with the name of our model. So, time to update the newly created migration file located at database/migrations directory.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('post_title');
            $table->string('slug');
            $table->longText('post_content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

After updating the migration file. Execute the given command to migrate the database.

php artisan migrate

Create a post submission form

Create a new post submission form or updating any existing view where we can apply the Laravel Form Validations.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif

                    <h3>Add New Post</h3>
                    <form method="post" name="addpost" id="addpost" action="{{ url('/post/store') }}">
                        {{ csrf_field() }}
                        <div class="form-group">
                            <label for="post_title">Title</label>
                            <input type="text" class="form-control" id="post_title" name="post_title">
                        </div>
                        <div class="form-group">
                            <label for="post_content">Content</label>
                            <input type="text" class="form-control" id="post_content" name="post_content">
                        </div>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

In the above code snippet, I’m adding one form on my dashboard view. This form is visible after the successful login. And I’m using the default authentication of Laravel.

Update route file

Now, we are updating our post controller route in routes/web.php

Route::resource('post', 'PostController');

Update Model

Now, time to update the post model as per our migration schema.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    protected $fillable = ['post_title', 'slug', 'post_content'];
}

Update Controller

Now, time to update our post controller where we update store function. store function is used to perform a validation and store the submitted value in the database after successful validations.

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request,[
        'post_title'=>'required',
        'post_content'=>'required'
    ]);

    $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();
}

Display Validations Error

If validations failed, then error shown in the view file. You can add given code snippet in your view.

...
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div><br />
@endif
...

You can place the above code at the top of your form.

All the errors are available on the views in Laravel with the help of \Illuminate\View\Middleware\ShareErrorsFromSession::class, Middleware. This middleware is defined in the web route. When the form validation failed then $errors variable filled with the error responses. And it flashed only one time in the view. On page refresh, $errors variable goes empty again.

Laravel Form ValidationsStop execution, If you want to stop the execution after the first validation occur then you can use the bail attribute.

...
$this->validate($request,[
    'post_title'=>'bail|required|min:6',
    'post_content'=>'required'
]);
...

In this example, if the required attribute fails, the min rule will not be checked. All the validation rules will validate in the order they are assigned, rules will be checked one by one. The min rule will not check if the required rule is failed.

Conclusion

In this article, I’m trying to explain to you how Laravel Form Validations work with the basic example. You can found more details on the basic validation here. With will discuss more on validation in future. You can check our other Laravel tutorials here. Please feel free to add the comment if any query.

Leave A Reply

Your email address will not be published.