Hi I'm using Laravel 7 and trying to submit based on the following condition:
if
isset($category) == true
then the method should be PUT
ifisset($category) == false
then method should change to POST
Update method which is PUT works fine with a response 302 changed from POST to PUT. The problem is if I'm going to submit via POST method based on given condition it says:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The PUT method is not supported for this route. Supported methods:GET, HEAD, POST.
Any suggestion how to do it, in the same form?
Here my codes:
<form action="{{ isset($category) ? route('categories.update',$category->id) : route('categories.store') }}" method="POST">
@csrf
@method('PUT')
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" value="{{ isset($category) ? $category->name : '' }}">
</div>
<div class="form-group">
<button class="btn btn-success">
{{ isset($category) ? 'Update category' : 'Add category' }}
</button>
</div>
</form>
I'm using Route::resource('categories','CategoriesController');
+--------+-----------+----------------------------+--------------------+------------------------------------------------------------------------+--------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+-----------+----------------------------+--------------------+------------------------------------------------------------------------+--------------+
| | POST | categories | categories.store | App\Http\Controllers\CategoriesController@store | web |
| | GET|HEAD | categories | categories.index | App\Http\Controllers\CategoriesController@index | web |
| | GET|HEAD | categories/create | categories.create | App\Http\Controllers\CategoriesController@create | web |
| | DELETE | categories/{category} | categories.destroy | App\Http\Controllers\CategoriesController@destroy | web |
| | PUT|PATCH | categories/{category} | categories.update | App\Http\Controllers\CategoriesController@update | web |
| | GET|HEAD | categories/{category} | categories.show | App\Http\Controllers\CategoriesController@show | web |
| | GET|HEAD | categories/{category}/edit | categories.edit | App\Http\Controllers\CategoriesController@edit | web |
+--------+-----------+----------------------------+--------------------+------------------------------------------------------------------------+--------------+
You need to condition the @method('PUT')
as well like below:
<form action="{{ isset($category) ? route('categories.update',$category->id) : route('categories.store') }}" method="POST">
@csrf
@if(isset($category))
@method('PUT')
@endif
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" value="{{ isset($category) ? $category->name : '' }}">
</div>
<div class="form-group">
<button class="btn btn-success">
{{ isset($category) ? 'Update category' : 'Add category' }}
</button>
</div>
</form>