A simple package to handle forms in Laravel with InertiaJS.
This is the backend pair of InertiaForm package.
- PHP ^8.1 || ^8.2
composer require khodakhah/larave-inertia-form
- Create a RequestForm class and extend it from InertiaFormRequest
- Create a static method named formInputs and return an instance of InertiaForm
UserFormRequest.php
use Khodakhah\InertiaForm\InertiaFormRequest;
class UserFormRequest extends InertiaFormRequest
{
public static function formInputs(\Khodakhah\InertiaForm\InertiaForm $form) : \Khodakhah\InertiaForm\InertiaForm{
$form->text('name', 'required');
$form->text('email', 'required|email');
$form->text('password', 'required|min:8');
return $form;
}
}
- Use
toInertia()
method to convert the form to an array and send it to the frontend. And usevalidated()
method to convert the form errors to an array and send it to the frontend.
class UserController extends Controller
{
use Khodakhah\InertiaForm\InertiaFormRequest;
public function create()
{
return Inertia::render('User/Create', [
'form' => UserFormRequest::toInertia()
]);
}
public function store(UserFormRequest $request)
{
User::create($request->validated());
return redirect()->route('users.index');
}
}
You can simply create a form by using InertiaForm
class, and assign it into a variable, or return it from a method.
class UserController extends Controller
{
use Khodakhah\InertiaForm\InertiaForm;
use Illuminate\Http\Request;
private function userForm(): InertiaForm
{
$form = new InertiaForm();
$form->text('name', 'required');
$form->text('email', 'required|email');
$form->text('password', 'required|min:8');
return $form;
}
public function create()
{
return Inertia::render('User/Create', [
'form' => $this->userForm()->toInertia()
]);
}
public function store(Request $request)
{
User::create(
$request->validate(
$this->userForm()->toValidation()
)
);
return redirect()->route('users.index');
}
}
If you have any issues, please create an issue in the issues section.
If you have any ideas or suggestions, please create a pull request in the pull requests section. I'll be happy to review and merge them.
- Clone the repository
- Run
composer install
- Run
composer test
to run the tests - Run
composer pint
to run the linter (syntax check) - Run
composer fix
to fix the linter errors - Run
composer analyse
to run phpstan analyse
The MIT License (MIT). Please see License File for more information.