GET (405) method not allowed [duplicate] - laravel

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

route laravel not defined

i have this route:
Route::get('blog/search', 'web\BlogController#localSearch')->name($this->prefix.'blogSingle.localSearch');
this route it´s inside group:
Route::group(['prefix' => $locale, 'where' => ['locale' => '[a-zA-Z]{2}']], function(){
//Route::get('/', 'Web\HomeController#index')->name($this->prefix.'home.index');
Route::get('/', 'Web\ManagerController#index')->name($this->prefix.'home.index');
Route::get('about', 'Web\AboutController#index')->name($this->prefix.'about.index');
Route::get('contact', 'Web\ContactController#index')->name($this->prefix.'contact.index');
Route::get('help', 'Web\HelpController#index')->name($this->prefix.'help.index');
Route::get('local/{url}', 'Web\LocalController#index')->name($this->prefix.'local.index');
Route::get('privacy-policy', 'Web\PrivacyController#index')->name($this->prefix.'privacy.index');
Route::get('managers', 'Web\ManagerController#index')->name($this->prefix.'manager.index');
Route::get('blog', 'Web\BlogController#index')->name($this->prefix.'blog.index');
Route::get('search', 'Web\SearchController#index')->name($this->prefix.'search.index');
Route::get('suggest-local', 'Web\SuggestController#index')->name($this->prefix.'suggest.index');
Route::get('terms-conditions', 'Web\TermController#index')->name($this->prefix.'term.index');
Route::get('blog/{url}', 'web\BlogController#show')->name($this->prefix.'blogSingle.show');
Route::get('blog/likeit/{id}', 'web\BlogController#likeit')->name($this->prefix.'blogSingle.likeit');
Route::get('blog/search', 'web\BlogController#localSearch')->name($this->prefix.'blogSingle.localSearch');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name($this->prefix.'password.reset');
Route::get('email/verify/{id}', 'Auth\VerificationController#verify')->name($this->prefix.'verification.verify');
});
}
but i need call to action form:
<form action="{{ route('blog/search') }}" method="get" class="fl-wrap" id="searchRestaurant">
and when send my form, returned this:
Route [blog/search] not defined. (View: C:\wamp64\www\guiaPaladar\resources\views\layouts\right_sidebar_blog.blade.php)
this error appear when blade load, so i can´t do anything
i don´t show my wrong, others routes i can use in other form, for example blog/likeit/{id} i used in href to add like in post blog...
i hope that anybody can help me, please. Sorry for my english
Thanks
If you are sure that the route blog/search is registered after using php artisan route:list to check. However, your change is not reflected; You may have to clear cache. Please use the following command:
php artisan route:clear

Route keep asking for parameter even if not set to receive any

I'm new to laravel and I'm having trouble with one of my web routes...
I grouped some routes with the auth middleware
Route::middleware(['auth:web'])->group(function ($router) {
Route::get('/news', [NewsController::class, 'news'])->name('news');
Route::get('/profile/{user_id}', [ProfileController::class, 'profile'])->name('profile');
Route::get('/marketplace', [MarketplaceController::class, 'marketplace'])->name('marketplace');
});
Before this issue, I have set a user_id parameter for the news route and then removed it the next day, now the news route keeps returning error saying it needs user_id.
here's my controller:
<?php
namespace App\Http\Controllers;
class NewsController extends Controller
{
public function news() {
return view('modules.news.news');
}
}
and since im using laravel-vue mix, my modules.news.news view looks like this:
#section('content')
<newsfeed inline-template>
<div>
...
...
</div>
</newsfeed>
#endsection
I've checked the web route, the controller, the blade, and I really can't see anything that requiring the news route to receive a parameter.
can someone point out where I went wrong?
Your route file might be cached, try running php artisan route:clear and see if this fixes the issue.

Vuejs: 400 BAD REQUEST on patch ajax with vue-resoure and Laravel

I don't know what I'm doing wrong, but my request URL for my Ajax Patch-request through Vue-resource is getting:
400 Bad Request
But this is only on the local environment!!! When I push it up to the server, it works!
Does anyone know why?
Here is my request:
var id = thing.id;
this.$http.patch('/api/things/' + id, thing).then(function(data){
console.log('edited to: '+data);
});
The request parameters should all be correct when looking at the Network tab in dev tools.
Here is my Route:
Route::resource('/api/things','ThingsPanelController');
Here is my Controller:
public function update(Request $request, $id)
{
Thing::findOrFail($id)->update([
'body'=>$request->body,
]);
return Response::json($request->all());
}
Could it be because the ID I added was 'api/things' + id and it sees it not as a wildcard in the route, but as a string! ?
This is my form I use. I prevent default and have the ajax request, so the form action shouldn't even be relevant...
<form action="update" #submit.prevent="doneEdit(thing)">
<input type="hidden" name="_method" value="PATCH">
<input type="text"
v-model="thing.body"
v-thing-focus="thing == editedThing"
#blur="doneEdit(thing)"
#keyup.esc="cancelEdit(thing)"
>
</form>
Check if the problem is persistent on your local server AS WELL AS your live server.
In this case the problem was only on the local server. Then just do this:
Stop artisan's serve, and execute: php artisan cache:clear
Then try again: php artisan serve and the problem should be solved.
The problem might be caused because of a program like CodeKit. Even though your php artisan serve would serve on ip 8000, CodeKit changes this for auto reload reasons. This messes up the ajax call uri's.

Displaying Error or alert message in laravel

I am new to Laravel. I want to display alert message. But i cannot display alert message once i hit url with localhost/social/alert. Please help me
Just a quick observation, which url do you intend to visit?
Is it localhost/social/alert or localhost/alert?
Also, try this
#if (session('info'))
<div class="alert alert-danger">
{{ session('info') }}
</div>
#endif
Let me know how that works out for you.
So in laravel 5.2, the errors, cookies, csrf tokens and so on are handled in the web middleware.
There are two ways to go about it.
Move your code into the web middleware
Route::group(['middleware' => 'web'], function () {
//code goes here
});
Move the classes from the web middleware in the $middlewareGroups variable in app/http/Kernel to $middleware
I prefer the first one

Laravel 4: Unable to generate a URL for the named route "login" as such route does not exist

I'm creating an authorization system in my Laravel 4 project. I am trying to use the auth "before" filter.
In my routes.php file, I have:
Route::get('viewer', array('before' => 'auth', function() {
return View::make('lead_viewer');
}));
Route::get('login', 'LoginController');
The before filter calls this line in the filters.php file:
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::route('login');
});
I can manually navigate to my login route. But the auth system isn't letting this happen. I've run composer dump-autoload a couple of times, so that isn't the problem. What am I doing, since I can actually load the login page if I do it manually?
I figure it out. Laravel is looking for a named route: I had to do this:
Route::get('login', array('as' => 'login', function() {
return View::make('login');
}));
An interesting, not very intuitive approach in Laravel. But there must be a reason Taylor did this that I'm not seeing.
To do what you were trying to do in your initial approach you could have just done:
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::to('/login');
});
and it would have worked just fine.
If you want to use named routes then you do what you posted in your answer to your own question. Essentially...more than one way to skin a cat.
Hope that helps
I know you've probably solved this by now but after stumbling across your post while trying to solve a similar problem, I wanted to share my thoughts...
Laravel is NOT looking for a named route for the guest method, it is expecting a path.
Your example works because because the named route and the path are the same i.e. "login". Try changing your URL to something other than 'login' and watch it fail.
If you want to use a named route you should use the route helper method as so...
if (Auth::guest()) return Redirect::guest( route('login') )
Hope that helps someone.

Resources