Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mionoeldavis's avatar

Reuse Forms?

Hi, what is the best way to re use forms? for example the user create and user edit form should be 100% the same, currently when i update one i need to update the other and visaversa so they remain same, i am pretty sure there is a better way to do that like to include the edit form on create or something?

Best Regards

0 likes
3 replies
tykus's avatar

You can easily create a form partial view which will be wrapped with the appropriate opening (and closing) form tags. The only "trick" is to pass an empty User instance ($user = new User;) to the create view template, so you can access the same $user variable:

<!-- users/create.blade.php -->
<form action="{{ route('users.create') }} method="POST">
    
    @include('users.form')

</form>
<!-- users/edit.blade.php -->
<form action="{{ route('users.update', $user) }} method="POST">
    @method('PUT')
    @include('users.form')
	
</form>
<!-- users/form.blade.php -->
@csrf
<div>
    <label for="email">Email</label>
    <input type="email" value="{{ old('email', $user->email) }}">
</div>
<!-- etc. -->
Snapey's avatar

This is me

https://talltips.novate.co.uk/laravel/simplify-laravel-crud-controllers

I always use the same view for edit and create operations. The trick, as @tykus says is to pass a new instance of the model into the view, however i go one small step further and minimise the controller also. Pass a new model into the edit controller method and let it render the view, and then when the new data comes back from the form, again get a new model and pass it into the update method along with the form data

martinbean's avatar

@mionoeldavis The principle is the same whether it’s front-end or back-end code: abstract re-used code.

For forms, you could either move it to an include or view component, where you optionally pass a model instance. When displayed in the create view (with no model), you’ll just see all the fields with empty values. On the edit view (with a model) then you’ll see all the fields, pre-populated with values from the model.

<!-- resources/views/users/create.blade.php -->
<x-user-form
    :action="route('users.store')"
    method="post"
/>
<!-- resources/views/users/edit.blade.php -->
<x-user-form
    :action="route('users.update', compact('user'))"
    method="put"
    :user="$user"
/>

Please or to participate in this conversation.