The PUT method is not supported for this route - laravel

I cannot submit form information through to store function in laravel controller. The form needs to create a - new - profile for a registered user.
I have even recreated the project, and redone the form - moving back into plain html as I suspect that the laravelCollective functions may be causing it but still the same error.
I have even rearranged the the form attributes as suggested in another post/thread.
I have even recreated the project, and redone the form - moving back into plain html as I suspect that the laravelCollective functions may be causing it but still the same error.
I have even rearranged the the form attributes as suggested in another post/thread.
The Form:
< form method="POST" enctype="multipart/form-data" action="{{ url('users/profile') }}" accept-charset="UTF-8" >
#csrf
...
// input fields here
...
< /form >
The Routes:
Route::resource('users/profile', 'ProfileController');
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('users', 'UserController');
Route::post('users/profile', 'ProfileController#store')->name('profile.store');
The ProfileController#store function:
//some code omitted
public function store(Request $request)
{
$this->validate($request, [
'firstname'=>'required',
'lastname'=>'required',
...
'desc'=>'required'
]);
//handle file upload
if($request->hasFile('cover_image')) {
//Get file name with extension
$fileNameWithExt = $request->file('cover_image')->getClientOriginalName();
//Just file name
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//Just Ext
$ext = $request->file('cover_image')->getClientOriginalExtension();
//FileName to Store
$fileNameToStore = $fileName.'_'.time().'_'.$ext;
//upload image
$path = $request->file('cover_image')->storeAs('public/users/'.auth()->user()->id.'cover_images/'.$request->input('firstname').'_'.$request->input('lastname').'_'.auth()->user()->id.'/',$fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
/*
*/
$profile = new Profile;
$profile->firstname = $request->input('firstname');
$profile->lastname = $request->input('lastname');
...
$profile->desc = $request->input('desc');
$profile->save();
return redirect('/users/profile');//->with('success','Profile Created');
}
The famous error:
Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException The PUT method is not supported for this
route. Supported methods: GET, HEAD, POST.
Not sure what is causing the error, help appreciated.

If I understand it correctly this is for store function right? then you don't have to put #method('PUT') inside your form it should POST. The route of store in resource is POST.
this is your code that i deleted the #method('PUT')
< form method="POST" enctype="multipart/form-data" action="{{ url('users/profile') }}" accept-charset="UTF-8" >
#csrf ...
// input fields here ...
< /form >
The Routes: Route::resource('users/profile', 'ProfileController');
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('users', 'UserController'); Route::post('users/profile', 'ProfileController#store')->name('profile.store');
and the PUT method is used for updating. When update in controller you need to pass id in your form that should look like this.
< form method="POST" enctype="multipart/form-data" action="{{ url('users/profile', $data->id) }}" accept-charset="UTF-8" >
#method('PUT')
#csrf ...
// input fields here ...
< /form >
I hope it helps!

you have problem in your routes file simply change your edit route to this route
Route::match(['put', 'patch'], 'the path you want /{id}','controllername#functionname');
you should notice that if you are new to laravel you should pass the id to this route as shown in this part {id} so that your edit function could display the previous data of it and also if you want to submit a the form it should have the put method and the html basic forms doesn't support that so you should find a way to submit it like using laravel collective or maybe put a hidden method in your form
if it doesn't work please give me a call

When using the Laravel resource method on a route, it makes things pretty specific in terms of what it is expecting. If you take a look at the chart on the manual, it is looking for a uri with the updating element id returned as part of the uri. The example looks like: /photos/{photo}. I'm not sure that this is how you've structured your html form.
You said you were using the LaravelCollective to get this working. This usually works fine, and has the massive advantage of easy form-model binding. But it helps to include the named route, which includes 'update' for the update resource. For example:
{!! Form::model($yourModel, array('route' => array('yourRoute.update',
$yourModel->id), 'method'=>'PUT', 'id'=>'Form'))!!}
I have not had an issue with the Collective using this method.

Related

getting errors The POST method

I have a problem with my edit page. When I submit I get this error:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods:
POST
.
I have no clue where it comes from as I am pretty new to Laravel.
web.php
Route::post('/admin/add_reseller','ResellerController#addReseller');
Controller.php
public function addReseller(){
return view ('admin.resellers.add_reseller');
}
add_reseller.blade.php
<form class="form-horizontal" method="post" action="" name="addreseller" id="addreseller">
{{ csrf_field() }}
Tip:
First of all, I would use named routes, that means you add ->name('someName') to your routes. This makes the use of routes way easier and if you decide that your url doens't fit you don't need to change it everywhere you used the route.
https://laravel.com/docs/7.x/routing#named-routes
e.g. Route::post('/admin/add_reseller',
'ResellerController#addReseller')->name('admin.reseller');
Problem:
What I see is, that you lack the value for the action attribute in your <form>. The action is needed, so that the right route is chosen, if the form gets submitted.
Solution:
I guess you just have to add action="{{route('admin.reseller')}}" for the attribute, so that the request goes the right route.
<form class="form-horizontal" method="post" action="" name="addreseller" id="addreseller">
Your action in the form is empty, you need to add the corresponding route there.
I'd suggest you to use named routes.
https://laravel.com/docs/7.x/routing#named-routes
In web.php
Route::post('/admin/add_reseller','ResellerController#addReseller')->name('admin.add.reseller');
and then in your blade file you could refer to the route using the route() function by passing the name of the route as an argument
<form class="form-horizontal" method="post" action="{{route('admin.add.reseller')}}" name="addreseller" id="addreseller">

update method issue(The POST method is not supported) in laravel

I want to create update method and this is the code:
Route::get("/allProducts/edit/{id}","AllproductController#edit")->name('Allproduct.edit');
Route::post("/allProducts/update/{id}","AllproductController#update")->name('Allproduct.update');
<form class="form-horizontal tasi-form" method="post" enctype="multipart/form-data"
action="{{ route('allProducts.update' , [ 'id'=>$allproduct->id ]) }}">
{{ csrf_field()}}
public function update(Request $request, $id)
{
$data = Allproduct::find($id);
$data->name = $request->name;
$data->save();
return redirect(route('allProducts.index'));
}
when I click on submit button it shows me :
"The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE" error!
what is the problem?
Your route names do not match.
in routes:
name('Allproduct.update');
in the form:
allProducts.update
Also, you can always check the name of the routes thanks to the console command:
php artisan route:list
if you want use method PUT:
you can change method in routes:
Route::post to Route::put
and add next in form:
<input type="hidden" name="_method" value="PUT">
OR
#method('PUT')
this is if your laravel version is 6 and if your version another, check correct way to use PUT method in forms at laravel.com/docs/6.x/routing with your version.
As said here
HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:
So your form should look like this:
<form class="form-horizontal tasi-form" method="post" enctype="multipart/form-data"
action="{{ route('Allproduct.update' , [ 'id'=>$allproduct->id ]) }}">
#csrf
#method('PUT')
You had a typo in your route name and it was missing the method field.
Change your route to this:
Route::put("/allProducts/update/{id}","AllproductController#update")->name('Allproduct.update');
This will work, but
i strongly recommend you read this laravel naming conventions, and then change the name of your controller and model to AppProductController, AppProduct.

How to pass params from laravel to ReactJS?

My application uses Lavarel and I have certain ReactJS components. Routing is done by Laravel. For a route /Users/<userid>, if the controller is UserController.php and view is userview.blade.php, how do I get the <userid> from the URL in my react component loaded in a div on userview.blade.php?
You can try out this library from Laracasts which allows you to pass server-side data (string/array/collection) to your JavaScript via a Facade in your Controller.
This may look something like this (haven't tested it, but you get the gist).
public function UserController($userid)
{
JavaScript::put([
'userid' => $userid,
]);
return View::make('yourview');
}
The docs further show how to access it from your view.
https://github.com/laracasts/PHP-Vars-To-Js-Transformer
UserController.php
you can access the userid and send it to view like this:
public function getUser($userid) {
return view('userview')->with('userid', $userid);
}
userview.blade.php
you can grab it (in some input) like this:
<input type="text" value="{{ $userid }}" />
This is, how I understand your problem. If it is not so, kindly correct me!!!

custom validation, method not allowed on error

<form method="post" action="{{action('PLAYERController#update', $ply->reg_no)}}">
{{csrf_field()}}
Getting method not allowed exception on custom validation with false return. Tried mentioning PUT, PATCH and DELETE inside csrf field. Still, does not work.
UPDATE
using post for form method. Using method_field('POST'). not defining get method for the update function. If I go back from the error page back to the form page and press refresh, then the validation message is displayed as it should.
UPDATE 2
Validator::extend('check_sold_amount', function($attribute, $value, $parameters, $validator) {
if(($value%5000)==0)
{
return true;
}
return false;
});
}
UPDATE 3
Controller code
public function update(Request $request, $reg_no)
{
//
$this->validate($request, [
'sold_amount' => 'required|check_sold_amount',
'sold_to_team'=>'required'
]);
$ply = Player::find($reg_no);
$ply->sold_amount = $request->get('sold_amount');
$ply->sold_to_team = $request->get('sold_to_team');
$team_name=$ply->sold_to_team;
$team=Team::find($team_name);
if($ply->category=='indian')
{
$team->indian_players=$team->indian_players+1;
}
else {
$team->foreign_players=$team->foreign_players+1;
}
$team->balance=$team->balance-$ply->sold_amount;
$ply->save();
$team->save();
//return view('player.index');
}
Method not allowed means you do not have a route set up for the request that happened. There are 2 possibilities:
The route for the form submission is not set up
The code you have shown us does not include any method_field(...), so it looks like you are doing a normal POST. So you need a corresponding POST route like:
Route::post('/some/path', 'PLAYERController#update');
The route for the failed validation response is not set up
I'm guessing this is the problem. Say you are on pageX, and you landed here via a POST. You have a post route set up, so that you can land on this page OK. Now from this page, you submit the form you have shown us, but validation fails. When that happens, Laravel does a GET redirect back to pageX. But you have no GET route set up for pageX, so you'll get a Method not allowed.
Along with your POST route for the current page, you need a GET route to handle failed validations.
Also, you say Tried mentioning PUT, PATCH and DELETE inside csrf field - as others pointed out, you should use method_field() to spoof form methods, eg:
<form ...>
{{ csrf_field() }}
{{ method_field('PATCH') }}
Laravel form method spoofing docs
UPDATE
Based on your comments, I think it is actually your initial POST that is failing. Checking your code again, I think your action() syntax is incorrect.
According to the docs, if the method specified in the action() helper takes parameters, they must be specified as an array:
action="{{ action('PLAYERController#update', ['reg_no' => $ply->reg_no]) }}"
If your update route using patch method (example Route::patch('.....');) then add this {{ method_field('PATCH') }} below {{csrf_field()}} in your update form
UPDATE
If you are not using PATCH method for the update route, try this :
Route::patch('player/update/{reg_no}', 'PLAYERController#update')->name('plyupdate');
and then in the form you can do like below :
<form method="POST" action="{{route('plyupdate', $ply->reg_no)}}">
{{csrf_field()}}
{{ method_field('PATCH') }}
//Necessary input fields and the submit button here
</form>
This way always works fine for me. If it still didn't work, maybe there's something wrong in your update method in the controller
UPDATE
Untested, in your update method try this :
public function update(Request $request, $reg_no) {
$input = $request->all();
$ply = Player::find($reg_no);
$validate = Validator::make($input, [
'sold_amount' => 'required|check_sold_amount',
'sold_to_team'=>'required'
]);
if ($validate->fails()) {
return back()->withErrors($validate)->withInput();
}
$ply->sold_amount = $request->get('sold_amount');
$ply->sold_to_team = $request->get('sold_to_team');
$team_name=$ply->sold_to_team;
$team=Team::find($team_name);
if($ply->category=='indian') {
$team->indian_players=$team->indian_players+1;
}
else {
$team->foreign_players=$team->foreign_players+1;
}
$team->balance=$team->balance-$ply->sold_amount;
$ply->save();
$team->save();
return view('player.index');
}
Don't to forget to add use Validator; namespace
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show the profile for the given user.
........................
Did you reference a validation request controller?
Hope this helps :)

Posting form in Laravel 4.1 and blade template

I'm having trouble posting forms using Laravel 4.1 with the blade template engine. The problem seems to be that the full URL including http:// is being included in the form action attribute. If I hard code the form open html manually and use a relative url, it works OK, however, when it has the full url, I am getting an exception.
routes.php
Route::any("/", 'HomeController#showWelcome');
HomeController.php
public function showWelcome()
{
echo($_SERVER['REQUEST_METHOD']);
return View::make('form');
}
Form opening tag in form.blade.php
{{ Form::open(["url" => "/","method" => "post","autocomplete" => "off"]) }}
{{ Form::label("username", "Username") }}
{{ Form::text("username", Input::old("username"), ["placeholder" => "john.smith"]) }}
{{ Form::label("password", "Password") }}
{{ Form::password("password", ["placeholder" => ""]) }}
{{ Form::submit("login") }}
{{ Form::close() }}
So if I go to my home dir / in the browser, I see the form that I have created. If I fill in the form details and click submit, I am simply taken to the same page - the request method is still GET as shown by echo($_SERVER['REQUEST_METHOD']);
I notice that the full
http://localhost/subdir/public/
url is used in the form markup. If I hardcode a form open tag in such as
<form action="/subdir/public/" method="post">
it works fine and $_SERVER['REQUEST_METHOD'] shows as post.
What am I doing wrong here?
You have created the route for the post?
example:
{{Form::open(["url"=>"/", "autocomplete"=>"off"])}} //No need to later add POST method
in Route.php
Route::post('/', 'YouController#postLogin');
you have not set up a route to handle the POST. You can do that in a couple of ways.
As pointed out above:
Route::post('/', 'HomeController#processLogin');
note that if you stick with your existing Route::any that the `Route::post needs to be before it as Laravel processes them in order (I believe).
You could also handle it in the Controller method showWelcome using:
if (Input::server("REQUEST_METHOD") == "POST") {
... stuff
}
I prefer the seperate routes method. I tend to avoid Route::any and in my login pages use a Route::get and a Route::post to handle the showing and processing of the form respectively.

Resources