0

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!

Lucas Dalmarco
  • 256
  • 2
  • 13
  • Possible duplicate of [Laravel 5.4 redirect taking method from request object](https://stackoverflow.com/questions/44499232/laravel-5-4-redirect-taking-method-from-request-object) To be honest, I'm not sure if I'm crazy about the thought of that being the best solution, but it was provided by a fairly high-rep user. There might just not be a good way to do it built in to Laravel. – Patrick Q Nov 30 '18 at 19:46

1 Answers1

1

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;
        }
    },
});
Lucas Ferreira
  • 858
  • 8
  • 18