In my project, I using laravel as api
UserController > profile()
need token to run
For example when I call it without token, laravel display error which "Route [login] not defined" and it’s right because we don’t have any template in laravel.
How can I return json response instead redirect to login page as html?
public function profile(): JsonResponse
{
//using protected method
return response()->json($this->guard()->user());
}
4
Answers
Open Authenticate file
app/Http/Middleware/Authenticate.php
add reference
put this code:
You can make middleware manually and in the middleware you can check user if exists. For example, if you use JWT token, then you can write like that as app/Http/Middleware/Authenticate.php :
For route partion:
So basically what you can do is you can create a customized Auth middleware which returns a JSON response.
Or you can use a simple condition in your function:
The code that you want to edit is located in app/Http/Middleware/Authenticate.php in the function redirectTo