Answer the question
In order to leave comments, you need to log in
How to merge two forms (Create and Update) into one?
I have two forms: create and edit post. I'm trying to combine them into one, how to do it right? I succeeded with assigning a variable in the controller for each method, and in the view I just checked which method was called. And what about checking the content - if there is a record, the Edit method is called, if there is no record, then Create?
controller:
public function create() {
return view('admin.categories.create');
}
public function edit($id) {
$cat = Category::find($id);
return view('admin.categories.create', compact('cat'));
}
<form action="{{ ($cat->title > 0 ? route('category.store') : route('category.update', ['id'=>$cat->id])) }}" method="post" enctype="multipart/form-data">
@csrf
@if ($cat->title > 0)
@method('PATCH')
@endif
<div class="form-group">
<label for="cat_id">Категория</label>
{{$cat->tite ?? ''}}
</div>
<div class="form-group">
<input name="category[title]" type="text" class="form-control" required value="{{ $cat->title ?? ''}}">
</div>
<input type="submit" value="Создать" class="btn btn-outline-success">
</form>
Answer the question
In order to leave comments, you need to log in
Here is my implementation
<form action="{{ (empty($cats) ? route('category.store') : route('category.update', ['id'=>$cats->id])) }}" method="post" enctype="multipart/form-data">
@csrf
@if (isset($cats))
@method('PATCH')
@endif
<div class="form-group">
<label for="cat_id">Категория</label>
{{$cats->tite ?? ''}}
</div>
<div class="form-group">
<input name="category[title]" type="text" class="form-control" required value="{{ $cats->title ?? ''}}">
</div>
<input type="submit" value="Создать" class="btn btn-outline-success">
</form>
1) Create a normal resource controller, with normal methods, routes and Model Binding
2) Save create edit views. It is strange to give a create view to the edit action
3) Move the form to include . Remove from it all these unnecessary checks.
4) Pass necessary routes and texts to include from create edit views
I usually have 1 method for both actions.
I just pass an empty model to the view, and "0" as the URL parameter.
public function edit($id) {
$cat = Category::findOrNew($id);
return view('admin.categories.edit', compact('cat'));
}
The error is that you are trying to get a value from a non-existent object ($cat->title > 0)
As an option, I think it’s more logical to use different files for the form wrapper, but put everything inside the forms into a separate view. This will eliminate confusion.
In current code
value="{{ $cats->title ?? ''}}"will reset values after incorrect form validation and will need to be filled out again. would be more logical
old('title', $cats->title ?? '')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question