Laravel Use Same Form for Create and Edit

Laravel 8 use same form for edit and create ,

You have to pass the object of the value to show the value on database. Let me show you every step:

public function create(){
$warehouse = new Warehouse();
return view('admin.warehouses.create', compact('warehouse'));
}
public function edit($id){
$warehouse = Warehouse::findOrFail($id);
return view('admin.warehouses.edit', compact('warehouse'));
}

Since, we have passed the $warehouse On both create.blade.php and edit.blade.php now we can use this same on both cases.

Now, on form, you have to use a value like this $warehouse->fieldName.

<input type="text" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email', $warehouse->email) }}">

If you want to use old values as well, you can use old(fieldName,$warehouse->fieldName)

Laravel use same form for create and edit

I like to use form model binding so I can easily populate a form's fields with corresponding value, so I follow this approach (using a user model for example):

@if(isset($user))
{{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
@else
{{ Form::open(['route' => 'createroute']) }}
@endif

{{ Form::text('fieldname1', Input::old('fieldname1')) }}
{{ Form::text('fieldname2', Input::old('fieldname2')) }}
{{-- More fields... --}}
{{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}

So, for example, from a controller, I basically use the same form for creating and updating, like:

// To create a new user
public function create()
{
// Load user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate');
}

// To update an existing user (load to edit)
public function edit($id)
{
$user = User::find($id);
// Load user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate')->with('user', $user);
}

Best practice to use same blade to add and edit content

If create/edit forms are almost the same it's a good idea to use one view and one model method for both forms. You can do something like this:

<form method="post" action="{{ route('article.'.(isset($article) ? 'update' : 'store' )) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="{{ isset($article) ? 'PUT' : 'POST' }}">
<input type="text" name="title" class="form-control" value="{{ $article->title or '' }}" />
<textarea name="content" class="form-control">{{ $article->content or ''}}</textarea>
<button type="submit">Envoyer</button>
</form>

Another cool way to handle this is to use Laravel Collective package. It has the form model binding feature which is perfect for this kind of situation.

And in a model I usually use updateOrCreate() which can handle both creating a new object and updating existing one.



Related Topics



Leave a reply



Submit