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
Related
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
});
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
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.
I have a contact form. On submit the POST request goes to a controller that handles the contact form (checks the request and emails the data). At the bottom of the controller I have this:
return back()->with('flash-message', 'Message!');
In the view I try to echo the message with
{{ session('flash-message') }}
This doesn't seem to work. The message is not in the session.
What could be wrong?
Im using:
Laravel version 5.2.7
please take Session variables with this way..
return redirect()->back()->with('flash-message','message');
and in View..
{{Session::get('flash-message')}}
I figured it out. It has to do with the Laravel 5.2 update. The middleware which is responsible for making that flash data available to all your views is not being utilized in normal Routes anymore. It was moved from the global middleware to the web middleware group. This post explains the issue and how to fix it.
Laravel 5.2 $errors not appearing in Blade
This post explains 2 ways to fix it:
In your kernel.php file, you can move the middleware \Illuminate\View\Middleware\ShareErrorsFromSession::class back to the protected $middleware property.
You can wrap all your web routes in the web middleware group (see below). Also place the Routes that handle the form here:
Route::group(['middleware' => 'web'], function() {
// Place all your web routes here...
});
You can do this.In the controller:
Session::flash('message','Empty input not accepted');
return back();
And in the view file to use this Session you can do same as above mentioned:
{{ \Session::get($message) }}
Hope this helps you....
I'm writing a webservice API (in laravel 4.2).
For some reason, the routing to one of my controllers is selectively failing based on HTTP method.
My routes.php looks like:
Route::group(array('prefix' => 'v2'),
function()
{
Route::resource('foo', 'FooController',
[ 'except' => ['edit', 'create'] ]
);
Route::resource('foo.bar', 'FooBarController',
[ 'except' => ['show', 'edit', 'create'] ]
);
}
);
So, when I try any of GET / POST / PUT / PATCH / DELETE methods for the
project.dev/v2/foo or project.dev/v2/foo/1234 urls, everything works perfectly.
But, for some reason, only GET and POST work for project.dev/v2/foo/1234/bar. The other methods just throw a 405 (MethodNotAllowedHttpException).
(fyi, I am issuing requests via the Advanced Rest Client Chrome extension.)
What's going on?
What am I missing?
Solved!
The answer can be found by running php artisan routes.
That showed me that DELETE and PUT/PATCH expect (require) a bar ID.
I happened to be neglecting that because there can only be one of this particular type of "bar". The easy fix it to simply add it to my URL's regardless, like project.dev/v2/foo/1234/bar/5678.
For the ones who are using Laravel versions > 4.2 use this :
php artisan route:list
This will give the list of routes set in your application. Check if routes for PUT and DELETE are allowed in your routes or not.
405 error is mostly because there is no route for these methods.
I don't know about older Laravel versions. But I use Laravel since 5.2 and it is necessary to include a hidden method input when using put, patch or delete.
Ex:
<input type="hidden" name="_method" value="PUT">
Check https://laravel.com/docs/5.6/routing#form-method-spoofing
Just add a hidden input field to your form
<input type="hidden" name="_method" value="PUT">
And keep form method as post
<form method="post" action="{{action('')}}">
If you want to use the method PUT in submit form you mast to see this link
https://laravel.com/docs/5.6/routing#form-method-spoofing
But if you use ajax in your project you mast to do anything like this:
<form>
#method('PUT')
// your_element
on your script add:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: {{ route('your_route', ':id') }},
type: 'POST',
data: data,
dataType: 'json',
cache: false,
}).done(function(data,status){
// anything
}).fail(function(){
// anything
});