search

Home  >  Q&A  >  body text

How to send custom error message from LoginController to frontend?

I added a check in LoginController to limit the maximum number of devices a user can connect to.

I added the following to the login() method of LoginController:

public function login(Request $request)
{
    // ... some code ...

    if ($this->attemptLogin($request)) {
        $user = Auth::user();
        if ($user->max_devices >= 5) {
            // if I dd() instead of returning this, it gets here
            return $this->sendMaxConnectedDevicesResponse($request);
        }
    }

    // ... some code ...
}

protected function sendMaxConnectedDevicesResponse(Request $request)
{
    throw ValidationException::withMessage([$this->username() => ['Device limit reached'])->status(403);
}

sendMaxConnectedDevicesResponse is a copy of sendLockoutResponse with my custom message, but I get a warning that I have an unhandled exception (Unhandled \Illuminate\ Validation\ValidationException< /代码>).

So how do I handle it like sendLockoutResponse so that it shows up as an error on the frontend instead of just ignoring it? Now, what happens is that even though it throws the error, it doesn't show it on the frontend and continues to log in as usual

I just didn't find a way to properly throw and catch custom errors

P粉101708623P粉101708623545 days ago728

reply all(1)I'll reply

  • P粉052686710

    P粉0526867102023-09-17 11:34:34

    In one of my projects I used this

    throw ValidationException::withMessages([
        'key' => 'error message',
    ]);

    In your, you can use

    throw ValidationException::withMessages([
        'device_limit' => 'Device limit reached',
    ]);

    So, on the frontend, you can use the device_limit key to get errors.


    In your login controller

    use Illuminate\Http\Request;
    use Illuminate\Http\Exceptions\HttpResponseException;
    
    class LoginController extends Controller
    {
        use AuthenticatesUsers;
    
        protected function authenticated(Request $request, $user)
        {
            if ($user->max_devices >= 5) {
                // Logout the user right after login
                $this->guard()->logout();
    
                // Throw an instance of HttpResponseException
                throw new HttpResponseException(
                    response()->json(['error' => 'Device limit reached'], 403)
                );
            }
        }
    }

    reply
    0
  • Cancelreply