DEV Community

Cover image for Laravel 8.0 Ajax Form Validation Example
devcse
devcse

Posted on • Updated on

Laravel 8.0 Ajax Form Validation Example

Today we will make ajax form validation, so that we can make our form validation without refreshing web page. so, let’s start…

Create a Laravel new project, run this command
composer create-project --prefer-dist laravel/laravel blog
Make Database connection
Go to the .env file and set the database name that you create in your MySQL dashboard admin panel

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_ajax_blog
DB_USERNAME=root
DB_PASSWORD=

Enter fullscreen mode Exit fullscreen mode

Create our custom route

routes/web.php

Route::get('post/create', [PostController::class, 'postCreateByAjax'])
    ->name('post.validation');
Route::post('post/store', [PostController::class, 'postStoreByAjax'])
    ->name('post.validation.store');

Enter fullscreen mode Exit fullscreen mode

Create Model
we will create Post model, run this command

php artisan make:model Post

Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title',
        'description'
    ];

}

Enter fullscreen mode Exit fullscreen mode

Create Controller
we will create controller named PostController, run this command

php artisan make:controller PostController

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{

    public function postCreateByAjax(){
        return view('ajax.ajax-create');
    }

    public function postStoreByAjax(Request $request){

        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'description' => 'required',
        ]);

        if ($validator->passes()) {

            Post::create($request->all()); // it store data to the DB

            return response()->json(['success'=>'Added new records.']);

        }

        return response()->json(['error'=>$validator->errors()]);

    }
}

Enter fullscreen mode Exit fullscreen mode

Get the full code: Laravel ajax form Validation

Top comments (0)