Laravel error "MethodNotAllowedHttpException" when trying to update row - php

I'm trying to do something very simple: When a user clicks a button, a column for a corresponding row is changed from 0 to 1.
The button goes to:
href="/redeem-coupon/{{ $coupon->coupon_code }}"
That route is set up as follows:
Route::post('/redeem-coupon/{coupon_code}', 'CouponController#redeemCoupon');
And the controller is:
public function redeemCoupon ($coupon_code)
{
$coupon = \DB::table('coupons')->where('coupon_code', $coupon_code)->first();
$coupon->redeemed = 1;
return redirect('/');
}
I have some existing code that uses a route to display some info from a row when the rows 'coupon_code' is working so everything else is working fine except for this part. Clicking the button gives
"Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException "

You are doing GET request while route is set for POST. Either change your route
Route::get(....
or switch to use HTML form and POST submission.

Change your route to intercept the get request instead of post:
Route::get('/redeem-coupon/{coupon_code}', 'CouponController#redeemCoupon');
EDIT:
The error MethodNotAllowedHttpException means that you are trying to access a non existing route, but sometimes you will get this error even if the route is setting correctly, in this case make sure that your route is above all other routes pointing to the same controller because some other routes may intercept your query.

Related

Why does my edit & delete methods return a "404 not found" when my index & create routes work

Laravel version has updated and the routes is now expecting an object instead of an id from when i last used it.
My Routes:
When I try to pass over the $item object which the method in the controller wants. I get a 404 not found and my logs aren't returning... meaning the function isn't running. When the $item obj is not passed over the function realizes that a parameter is missing thus the method is recognized by the blade as being the same as the one in the controller.
Calling the edit function in Blade:
Controller Code:
I appreciate any help whatsoever.
The order of your routes is probably wrong
when you first define the show route with /item/{item} and then create with /item/create laravel will think the "create" is the id (or reference)
best way is to have
the index
create
....
show
Code Example correct
Route::get('/', ProductIndex::class)->name('product.index');
Route::get('/new', ProductCreate::class)->name('product.create');
Route::get('/{product}', ProductShow::class)->name('product.show');
Code Example wrong
Route::get('/', ProductIndex::class)->name('product.index');
Route::get('/{product}', ProductShow::class)->name('product.show');
Route::get('/new', ProductCreate::class)->name('product.create');

Laravel returns MethodNotAllowedHttpException on routing does not exist

I created a route for buy an item in laravel 5.7
Route::post('/buy/item', "userController#buy_item")->name('buy_item_form');
Everything works fine but when I refresh the page(replace to GET Request) I got an
MethodNotAllowedHttpException.
The GET route not exist, Its must return an 404 error.
I dont understant why its return me this exception.
You are using a post, with post you have a #csrf token. when you click on refresh, you are doing a GET method instead of a post and for hence you get the method not allow exception. If you are not sending data you can change it to a get [Route::get] method.
If you want to accept the 2 methods [post,get] to have a better experience and manage the possible errors. You can accept the 2 methods on the route like:
Route::match(array('GET','POST'),'/buy/item', 'userController#buy_item')->name('buy_item_form');
And on the controller, define what to do base on the method.
if (Request::isMethod('get')){
// redirect user
}
if (Request::isMethod('post')){
// do logic for post method
}

Dynamic routes doesn't work in Laravel 5.5

I have some problem with dynamic routes.
I just tried add likes value in posts table to some post.
web.php
Route::get('post/{$id}/like', 'PostController#like')->name('post.like');
Route::resource('post', 'PostController');
And i define 1 custom method in resource controller PostControleler.
PostController#like
public function like($id)
{
$post = Post::find($id);
$post->likes++;
$post->save();
return redirect()->back();
}
and link in blade php view
Like
When clicking on a link, nothing happen, just displayed 404
Sorry, the page you are looking for could not be found.
Why that dynamic route doesn't work.
P.S.
That code works if i replace method to show instead like (it means that the custom method is hindered by something, the code itself is working)
Thanks in advance.
you need to replace your href by this below and make shure if $post it's $post of id value or replace it with $post->id
Like
and change get by post (here your are send data to the server that means you will post $id)
Route::post('/post/{$id}/like', 'PostController#like')->name('post.like');
Damn....i just forgot delete $ sign in custom route.
Should be:
Route::get('post/{post}/like', 'PostController#like')->name('post.like');

Laravel error upon submitting a form: MethodNotAllowedHttpException in RouteCollection.php line 218. What could this be due to?

There is a form in my view, from where, on clicking submit, data is taken to ajax script which is supposed to invoke the controllers specified in the post routes in routes.php. The controllers are expected to process the received data and throw the result back to the view. Why is this error occurring immediately after submitting the form and things aren't working as expected>
Check your routes.php file. Make sure that the method your using corresponds with what you have allowed.
Here is the laravel documenation for routes
For example, if your request is a GET request, the call should look like this in the routes file:
Route::get('/test-get-url', function () {
// Matches The "/test-get-url" URL using a GET method
});
And for post
Route::post('/test-post-url', function () {
// Matches The "/test-post-url" URL using a POST method
});
Go to terminal/cmd..whichever you using and type
php artisan route:list
this will list all your routes and check at what route your is being submitted.Note the corresponding method to be used in the Method column and use that method while submitting form.I'm assuming it's PUT method(which is most likely).Ex--
Use method attribute if you're using simple HTML code like--
<form action="{{route='..'}}" method="PUT">
or if you're using form helper then use--
{!! Form::open($post, ['route' => ['..'], 'method' => 'PUT']) !!}
Go to your route.php file and check
Route::get('someroute',['uses'=>'somecontroller#function_get','as'=>'some_get']);
Route::post('someroute',['uses'=>'somecontroller#funtion_post','as'=>'some_post']);
make sure if your are using (as) in you routes its different and also where you use your ajax you properly define your route where you want to post your form data and it's type is same as you mention in routes and one more thing check you properly use (;) in your code
hope this will help you fell free to ask your query

laravel 4 route not found - defaults to show method

I've had this working but now a route is no longer found and I can't see why.
In a javascript function I am making an ajax post to the function with this url:
url: '/customers/storeajax',
In my routes.php file I have the following routes:
Route::post('customers/storeajax', array('as'=>'storeajax', 'uses' => 'CustomersController#storeAjax'));
Route::post('customers/updateajax/{id}', array('as'=>'updateajax','uses' => 'CustomersController#updateAjax'));
Route::resource('customers', 'CustomersController');
Now when I try to POST to the storeajax route I get a ModelNotFoundException which to me means the route could not be found so it defaults to the default customers controller show method - in the error log I can see the following entry:
#1 [internal function]: CustomersController->show('storeajax')
confirming its treating the storeajax as a parameter.
I've placed my additional routes above the default resource route
I've had this working before I can't see where I've gone wrong.
In addition these routes are placed in a group:
Route::group(array('before' => 'sentryAuth'), function () {}
which simply ensures user is logged on. To test though I've removed outside the group and at the top of the file but still they don't work.
The url in my browser is coming up correctly as: http://greenfees.loc/customers/storeajax (which I can see in firebug console
I'm using POST as the ajax method - just to confirm
Can anyone see why this route doesn't work and what I've missed?
Update:
Here's the method inside the controller:
public function storeAjax()
{
$input = Input::all();
$validation = Validator::make($input, Customer::$rules);
if ($validation->passes())
{
$customer = $this->customer->create($input);
return $customer;
}
return Redirect::route('customers.create')->withInput()
->withErrors(validation)
->with('message', 'There were validation errors.');
}
I'm 99% certain though that my route is not reaching this method (i've tested with a vardump inside the method) and the issue relates to my route customer/storeajax cannot be found.
What I think is happening is as customer/storeajax is not found in the list of routes starting with customer it is then defaulting to the resource route that appears on the list and thinks this is a restful request and translating it as customer route which defualts to the show method and using the storeajax as the parameter which then throws the error modelnotfoundexception because it cant find a customer with an id of 'storeajax'
This is evidence by the log detailing a call to the show method as above.
So for some reason my route for '/customers/storeajax' cannot be found even though it appears to be valid and appears before the customers resource. The modelnotfoundexception is a red herring as the cause is because of the routes defaulting to the resource constroller of customers when it cant find a route.
A route not being found raises a NotFoundHttpException.
If you are getting a ModelNotFoundException is because your route is firing and your logic is trying to find a Model, wich it can't somehow, and it is raising a not found error.
Are you using FindOrFail()? This is an example of method that raises this exception. BelongsToMany() is another one that might raise it.
I solved this by renaming the method in the controller to 'newAjax' and also updating the route to:
Route::post('customers/new', array('as'=>'newajax','uses' => 'CustomersController#newAjax'));
the terms store I assume is used by the system (restful?) and creating unexpected behaviour. I tested it in a number of other functions in my controller - adding the term store as a prefix to the method then updating the route and each time it failed.
Something learned.

Categories