Laravel React JS Form Validation Example

By Hardik Savani April 16, 2024 Category : Laravel

Hi Friends,

In this example, you will learn laravel react js form validation. it's a simple example of laravel react js form submit example. We will use laravel 9 react js form validation. This post will give you a simple example of form validation in react js laravel.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

In this tutorial, we will use laravel breeze, inertia js, vite and tailwind CSS to create react form validation in laravel app. we will create "posts" table with title and body columns. then we will create a simple form with validation using react.

So, let's follow the below step to do react js form submit with laravel vite. you can see below a preview screenshot of the example as well.

Preview:

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Auth with Breeze

Now, in this step, we need to use composer command to install breeze, so let's run bellow command and install bellow library.

composer require laravel/breeze --dev

now, we need to create authentication using bellow command. you can create basic login, register and email verification using react js. if you want to create team management then you have to pass addition parameter. you can see bellow commands:

php artisan breeze:install react

Now, let's node js package:

npm install

let's run vite, you have to keep start this command:

npm run dev

now, we need to run migration command to create database table:

php artisan migrate

Step 3: Create Migration and Model

Here, we need create database migration for posts table and also we will create model for posts table.

php artisan make:migration create_posts_table

Migration:

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('posts', function (Blueprint $table) {

$table->id();

$table->string('title');

$table->text('body');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

}

php artisan migrate

now we will create Post.php model by using following command:

php artisan make:model Post

App/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

use HasFactory;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'title', 'body'

];

}

Step 4: Create Route

In third step, we will create routes for react js form submit. so create two routes here.

routes/web.php

<?php

use Illuminate\Foundation\Application;

use Illuminate\Support\Facades\Route;

use Inertia\Inertia;

use App\Http\Controllers\PostController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('posts/create', [FileController::class, 'create'])->name('posts.create');

Route::post('posts/create', [FileController::class, 'store'])->name('posts/store');

Route::get('/', function () {

return Inertia::render('Welcome', [

'canLogin' => Route::has('login'),

'canRegister' => Route::has('register'),

'laravelVersion' => Application::VERSION,

'phpVersion' => PHP_VERSION,

]);

});

Route::get('/dashboard', function () {

return Inertia::render('Dashboard');

})->middleware(['auth', 'verified'])->name('dashboard');

require __DIR__.'/auth.php';

Step 5: Create Controller

In this step, we will create PostController file and add following code on it.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Inertia\Inertia;

use App\Models\Post;

use Illuminate\Support\Facades\Validator;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function create()

{

return Inertia::render('Posts/Create', [

'message' => session('message'),

]);

}

/**

* Show the form for creating a new resource.

*

* @return Response

*/

public function store(Request $request)

{

Validator::make($request->all(), [

'title' => ['required'],

'body' => ['required'],

])->validate();

Post::create($request->all());

return redirect()->route('posts.create')

->with('message', 'Post created successfully!');

}

}

Step 6: Create React Pages

Here, in this step we will create Create.jsx file with form.

so, let's create it and add bellow code on it.

resources/js/Pages/Posts/Create.jsx

import React from 'react';

import Authenticated from '@/Layouts/Authenticated';

import { Head, useForm, Link, usePage } from '@inertiajs/inertia-react';

export default function Dashboard(props) {

const { message } = usePage().props

const { data, setData, errors, post } = useForm({

title: "",

description: "",

});

function handleSubmit(e) {

e.preventDefault();

post(route("posts.store"));

data.title = "";

data.body = "";

}

return (

<Authenticated

auth={props.auth}

errors={props.errors}

header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Laravel React JS Form Validation Example - ItSolutionStuff.com</h2>}

>

<Head title="Posts" />

<div className="py-12">

<div className="max-w-7xl mx-auto sm:px-6 lg:px-8">

<div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">

<div className="p-6 bg-white border-b border-gray-200">

{ message &&

<div className="bg-teal-100 border-t-4 border-teal-500 rounded-b text-teal-900 px-4 py-3 shadow-md my-3" role="alert" >

<div className="flex">

<div>

<p className="text-sm">{ message }</p>

</div>

</div>

</div>

}

<form name="createForm" onSubmit={handleSubmit}>

<div className="flex flex-col">

<div className="mb-4">

<label className="">Title</label>

<input

type="text"

className="w-full px-4 py-2"

label="Title"

name="title"

value={data.title}

onChange={(e) =>

setData("title", e.target.value)

}

/>

<span className="text-red-600">

{errors.title}

</span>

</div>

<div className="mb-0">

<label className="">Body</label>

<textarea

type="text"

className="w-full rounded"

label="body"

name="body"

errors={errors.body}

value={data.body}

onChange={(e) =>

setData("body", e.target.value)

}

/>

<span className="text-red-600">

{errors.body}

</span>

</div>

</div>

<div className="mt-4">

<button

type="submit"

className="px-6 py-2 font-bold text-white bg-green-500 rounded"

>

Save

</button>

</div>

</form>

</div>

</div>

</div>

</div>

</Authenticated>

);

}

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Also keep run following command for vite:

npm run dev

If you want to build then you can run following command:

npm run build

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000

Then after you have to go to the below URL:

http://localhost:8000/posts/create

now it works...

I hope it can help you...

Tags :
Shares