Laravel 5.4 routes/api.php POST MethodNotAllowedHttpException - php

I am writting APIs for android/ios using Laravel 5.4. My simple webservice signUp which is working perfectly on localhost not working on live server and giving
MethodNotAllowedHttpException on POST methods
GET call works perfect .
Route code
Route::post('/signUp',['uses'=>'API_UserController#userSignUp']);
Attached is screen shot link of my postman.
https://i.stack.imgur.com/060IF.png

here is quick example of flow try this
<form action="{{url('v1/userSignUp')}}" class="validation" method="post"
accept-charset="utf-8">
{{ csrf_field() }}
<div>
// your required form field
<input type="submit" value="Add Category" class="btn btn-primary" />
</div>
</form>
and in your route add this
Route::get('/signUp', function () {
return view('yourviewpagename');
});
Route::post('/signUp','API_UserController#userSignUp');
and in your API_UserController
public function userSignUp()
{
dd(request->all());
}

#Mujeeb Ur Rehman Post method is use to send data and get method is use to access data in view or just to render view.
eg:-route:post('/home',xxController#xx);
route:get('/home1',xxController#xx);
error which you are getting is because suppose if you url it like this localhost/xx/home your framework think to access data or post data framework get confuse in this

just use like this
Route::group(['prefix' => 'v1'], function () {
Route::post('/signUp','API_UserController#userSignUp');
});
when you hit via postman tour URL is http://your_domain/api/v1/signUp so just add a prefix it will automatically add with your URL. in route group u can also use many other things like namespace, middleware etc. Example :
Route::group(['namespace' => 'any_depend_on_your_project_structure', 'middleware' => 'any_middleware', 'prefix' => 'v1'], function() {
// your routes
});

Related

Laravel 9 html form submit throws 405. Expects PUT, request is GET

I'm trying to create a simple CRUD application with Laravel 9. I've run into a problem with HTML forms. I've created a page where you can edit data on rabbits existing in my database.
My form
<form name="editRabbitForm" action="{{ url('/rabbit/update') }}" method="PUT">
{{ csrf_field() }}
<!-- here be input fields -->
<button type="submit" class="btn btn-success">Save</button>
<a type="button" href="/rabbits" class="btn btn-danger">Cancel</a>
</form>
web.php routes
<?php
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\QuoteController;
use App\Http\Controllers\RabbitController;
use Illuminate\Support\Facades\Route;
Route::get('/rabbits', [RabbitController::class, 'index']);
Route::get('/rabbit/edit/{id}', [RabbitController::class, 'edit']);
Route::put('/rabbit/update', [RabbitController::class, 'update']);
RabbitController.php
<?php
namespace App\Http\Controllers;
use App\Models\Rabbit;
use Illuminate\Http\Request;
class RabbitController extends Controller
{
public function index() {
return view('rabbits.index', ['rabbits' => Rabbit::all()]);
}
public function edit($id) {
return view('rabbits.edit', ['rabbit' => Rabbit::where('breed_id', $id)->first()]);
}
public function update(Request $request) {
echo("SOME SORT OF RESULT!");
var_dump($request);
}
}
Before I even hit the controller I get an exception reading:
The GET method is not supported for this route. Supported methods: PUT.
I really don't get what I'm doing wrong in this scenario
As stated above in my comment:
To send a put request you will need to change the method to POST and add #method('PUT') in your form. This will insert a hidden input for the method. Laravel will then automatically route this request to the method specified by the put route in your routes file.
This is needed because as #ADyson writes, browsers are limited to GET and POST request.
And last but not least, browsers or in this case HTML forms are stupid.
Maybe someday this will be changed, who knows.

How to use Basic Routing methods in Laravel?

I have get some documents from Laravel Documentation.But i can't get details clearly from that. There are lot of routing methods and how to use that for my requirements? Commonly most people are using this, but what are the other routing methods?
Route::get()
Route::post()
How to pass the message or values through this Routing? Using Controller like this is a only way?
Route::get('/app', 'AppController#index');
Types of Routing in Laravel
There are some Routing methods in Laravel, There are
1. Basic GET Route
GET is the method which is used to retrieve a resource. In this example, we are simply getting the user route requirements then return the message to him.
Route::get('/home', function() { return 'This is Home'; });
2. Basic POST Route
To make a POST request, you can simply use the post(); method, that means when your are submitting a Form using action="myForm" method="POST", then you want to catch the POST response using this POST route.
Route::post('/myForm', function() {return 'Your Form has posted '; });
3. Registering A Route For Multiple Verbs
Here you can retrieve GET request and POST requests in one route. MATCH will get that request here,
Route::match(array('GET', 'POST'), '/home', function() { return 'GET & POST'; });
4. Any HTTP Verb
Registering A Route Responding To Any HTTP Verb. This will catch all the request from your URL according to the parameters.
Route::any('/home', function() { return 'Hello World'; });
Usage of Routing in Laravel
When your are Using the Route::, Here you can manage your controller functions and views as follows,
1. Simple Message Return
You can return a simple message which will display in the webpage when user request that URL.
Route::get('/home', function(){return 'You Are Requesting Home';});
2. Return a View
You can return a View which will display in the webpage when user request that URL
// show a static view for the home page (app/views/home.blade.php)
Route::get('/home', function()
{
return View::make('home');
});
3. Request a Controller Function
You can call a function from the Controller when user request that URL
// call a index function from HomeController (app/Http/Controllers)
Route::get('/home', 'HomeController#index');
4. Catch a value from URL
You can catch a value from requested URL then pass that value to a function from Controller. Example : If you call public/home/1452 then value 1452 will be cached and will pass to the controller
// call a show function from HomeController (app/Http/Controllers)
Route::get('/home/{id}', 'HomeController#show');
You can get help about routing from Laravel.
There are 4 methods ofform data sending that you must know --
Route::get for <form method="GET">
Route::post for <form method="POST">
Route::put for <form method="PUT"> -- This one is for updating your database, I recommend you to use laravelcollective/html, like this -- {!! Form::open(['method' => 'PUT']) !!}, but in your web browser you can find the method as POST only
Route::delete for <form method="DELETE"> -- This one is for deleteing a field in your database, I recommend you to use laravelcollective/html, like this -- {!! Form::open(['method' => 'DELETE']) !!}, but in your web browser you can find the method as POST only
There are many much you have to know about Laravel Routing, like CRUD, etc.

TokenMismatchException after using web middleware

im adding csrf_field to all my forms by default and it was working fine , i decided to store some data in session so i've grouped some routes and used web middlewar on them
Route::group(['middleware' => ['category' , 'web']], function () {
Route::get('/', 'HomeController#index');
Route::get('/dashboard', 'DashboardController#index')->name('dashboard');
})
now when i submit a form i get this error
TokenMismatchException in VerifyCsrfToken.php line 67:
but they work fine if i remove web middleware !!
im using database drive for my sessions ... i dont know if that's relevant
Remove web middleware, that should fix the problem.
Since 5.2.27 web middleware applies automatically to all routes (in 5.3 to all routes in routes/web.php) and you shouldn't add it manually.
If the form is not token field _token
<form method="POST" action="">
{{ csrf_field() }}
...
</form>

laravel 5, form submit redirect to unknown url value

I just wondering in my project. I have a form that can be access at localhost/app/esetting/mymail and this is the code in the view:
....
<form action="{{ url( 'app/esetting/emailautomsave' ) }}" class="form-horizontal" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
...
<input type="submit" value="save">
</form>
but when I try to click for form submission, I expect it to go to app/esetting/emailautomsave and calls it controller which is on my SettingsController.php.
public function postEmailautomsave(Request $request){
...
}
but it redirects to localhost/app/mymail? and give me this error:
NotFoundHttpException in Controller.php line 93:
Controller method not found.
this sounds weird on my end. can anyone have an idea about this? I am sure I have done the right this specially on my routes.php
Route::group([ 'prefix' => 'app', 'middleware' => 'auth' ], function() {
....
Route::controller('esetting', 'SettingController');
Route::get( 'esetting/mymail', 'SettingController#viewEmailAutom' ); // view for the form to display
....
Just simply define:
Route::post('esetting/mymail/emailautomsave', 'SettingController#postEmailautomsave');
I know that You'll say: "I've defined Route::controller, so it will look for it atuomatically."
But for me is best to have routes defined exactly.
also if:
it redirects to localhost/app/mymail? and give me this error:
NotFoundHttpException in Controller.php line 93: Controller method
not found.
maybe it means that some middleware is redirecting You there?
You can check it by simply doing this:
public function postEmailautomsave(Request $request){
die('test');
...
}
if it will redirect so it mean that some function was called before and redirect browser to app/mymail.
If you use Route::controller you need to define you methods according to the route.
E.g.
Route::controller('esetting', 'SettingController');
Will look for SettingController#getIndex when you visit http:://yoursite.com/esetting
To reach SettingController#postEmailAutomsave() you would need to go to the route http:://yoursite.com/esetting/emmail/automsave
I have not used Route::controller myself, I got used too (and now prefer) naming them individually.
But this should do the trick.
Laravel 5.1 docs

Error 405 (Method Not Allowed) Laravel 5

Im trying to do a POST request with jQuery but im getting a error 405 (Method Not Allowed), Im working with Laravel 5
THis is my code:
jQuery
<script type="text/javascript">
$(document).ready(function () {
$('.delete').click(function (e){
e.preventDefault();
var row = $(this).parents('tr');
var id = row.data('id');
var form = $('#formDelete');
var url = form.attr('action').replace(':USER_ID', id);
var data = form.serialize();
$.post(url, data, function (result){
alert(result);
});
});
});
</script>
HTML
{!! Form::open(['route' => ['companiesDelete', ':USER_ID'], 'method' =>'DELETE', 'id' => 'formDelete']) !!}
{!!Form::close() !!}
Controller
public function delete($id, \Request $request){
return $id;
}
The Jquery error is http://localhost/laravel5.1/public/empresas/eliminar/5 405 (Method Not Allowed).
The url value is
http://localhost/laravel5.1/public/empresas/eliminar/5
and the data value is
_method=DELETE&_token=pCETpf1jDT1rY615o62W0UK7hs3UnTNm1t0vmIRZ.
If i change to $.get request it works fine, but i want to do a post request.
Anyone could help me?
Thanks.
EDIT!!
Route
Route::post('empresas/eliminar/{id}', ['as' => 'companiesDelete', 'uses' => 'CompaniesController#delete']);
The methodNotAllowed exception indicates that a route doesn't exist for the HTTP method you are requesting.
Your form is set up to make a DELETE request, so your route needs to use Route::delete() to receive this.
Route::delete('empresas/eliminar/{id}', [
'as' => 'companiesDelete',
'uses' => 'CompaniesController#delete'
]);
Your routes.php file needs to be setup correctly.
What I am assuming your current setup is like:
Route::post('/empresas/eliminar/{id}','CompanyController#companiesDelete');
or something. Define a route for the delete method instead.
Route::delete('/empresas/eliminar/{id}','CompanyController#companiesDelete');
Now if you are using a Route resource, the default route name to be used for the 'DELETE' method is .destroy. Define your delete logic in that function instead.
In my case the route in my router was:
Route::post('/new-order', 'Api\OrderController#initiateOrder')->name('newOrder');
and from the client app I was posting the request to:
https://my-domain/api/new-order/
So, because of the trailing slash I got a 405. Hope it helps someone
If you didn't have such an error during development and it props up only in production try
php artisan route:list to see if the route exists.
If it doesn't try
php artisan route:clear to clear your cache.
That worked for me.
This might help someone so I'll put my inputs here as well.
I've encountered the same (or similar) problem. Apparently, the problem was the POST request was blocked by Modsec by the following rules: 350147, 340147, 340148, 350148
After blocking the request, I was redirected to the same endpoint but as a GET request of course and thus the 405.
I whitelisted those rules and voila, the 405 error was gone.
Hope this helps someone.
If you're using the resource routes, then in the HTML body of the form, you can use method_field helper like this:
<form>
{{ csrf_field() }}
{{ method_field('PUT') }}
<!-- ... -->
</form>
It will create hidden form input with method type, that is correctly interpereted by Laravel 5.5+.
Since Laravel 5.6 you can use following Blade directives in the templates:
<form>
#method('put')
#csrf
<!-- ... -->
</form>
Hope this might help someone in the future.
When use method delete in form then must have to set route delete
Route::delete("empresas/eliminar/{id}", "CompaniesController#delete");
I solved that issue by running php artisan route:cache which cleared the cache and it's start working.
For Laravel 7 +, just in case you run into this, you should check if the route exists using
php artisan route:list
if it exists then you need to cache your routes
php artisan route:cache

Categories