skip to Main Content

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


  1. Chosen as BEST ANSWER

    Open Authenticate file app/Http/Middleware/Authenticate.php

    add reference

    use Closure;
    use IlluminateSupportFacadesAuth;
    

    put this code:

    public function handle($request, Closure $next, ...$guards)
    {
        if (!Auth::guard('api')->check()) {
            return response()->json(['message' => 'Error Message!']);
        }
    
        return $next($request);
    }
    

  2. 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 :

       public function handle($request, Closure $next, $guard = null)
        {
    
            /* Check is token filled */
            if (!Auth::check()) {
                return response()->json([
                    'success' => false,
                    'status' => 401,
                    'message' => 'Bad authorization',
                    'data' => []
                ], 401);
    
            }
    
            return $next($request);
        }
    
    

    For route partion:

    Route::group([
        'middleware' => 'auth'
    ], function () {
      Route::get('/profile', 'User@profile');
    });
    
    Login or Signup to reply.
  3. 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:

      if (Auth::check()){
          //if logged in user exists
      } else {
          //if logged in user does not exist
      }
    
    Login or Signup to reply.
  4. The code that you want to edit is located in app/Http/Middleware/Authenticate.php in the function redirectTo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search