T
T
ThreegunD2017-03-24 00:57:05
Laravel
ThreegunD, 2017-03-24 00:57:05

Middleware - returning json string?

There is a button to add a product, only authorized users can add.
An AJAX request is added, the request stumbles upon middleware and it is necessary to return an error in case of failure.
Own in the documentation only about redirect is written, but the redirect does not suit me.
ps my thoughts on this subject are as follows: It is necessary to throw an exception, make a handler for this exception and it will already return an error code for example. Is it true at least I think or how to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kulik, 2017-03-24
@ThreegunD

An AJAX request will return 401 Unauthorized and not a redirect. Handle error response.
All the same, no.
It's better to write your own middleware, like this:

public function handle($request, Closure $next)
    {
        if ($this->guard->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest(URL::route('auth'));
            }
        }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question