How to send custom error message from LoginController to frontend?
P粉101708623
P粉101708623 2023-09-16 12:57:17
0
1
629

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粉101708623
P粉101708623

reply all(1)
P粉052686710

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)
            );
        }
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!