Reputation: 333
I'm new in Laravel!!
I have a js that send a request DELETE to my controller:
$.ajax({
url: link,
method: 'DELETE',
data: {
_token: $('input#_token').val(),
},
Than my controller return redirect
public function destroy(User $user)
{
$this->repository->delete($user->id);
return redirect()->to(route('users.index'));
}
This route "users.index" has the "GET" method, but the redirect is considering the DELETE method, resulting in this error:
DELETE http://localhost:8000/users 405 (Method Not Allowed)
Can i change the method using in redirect?
Tks!
Upvotes: 0
Views: 166
Reputation: 888
Ajax request will always follow redirects (actually, there's a work around), so you probably should change your controller to avoid redirects if this is an ajax request.
use Illuminate\Http\Request;
# [...]
public function destroy(Request $request, User $user)
{
$this->repository->delete($user->id);
if ($request->ajax()) {
return $user;
}
return redirect()->to(route('users.index'));
}
If this controller only receives ajax requests, you can make it simpler.
public function destroy(Request $request, User $user)
{
$this->repository->delete($user->id);
# or return whatever you want with: response()->json($contents);
return $user;
}
[UPDATED] Making redirects after ajax
As @PatricQ mentioned, you might want to make the redirect after the ajax call. If this is the case, I suggest that you create a response format that your javascript understands and makes a redirect.
An example would be to return the redirect URL:
return response()->json(['redirect' => true, 'to' => route('users.index')]);
This way, in your javascript you would check for the redirect flag.
$.ajax({
url: link,
method: 'DELETE',
data: {
_token: $('input#_token').val(),
},
success: function (response) {
if (response.redirect) {
window.location.href = response.to;
}
},
});
Upvotes: 1