menu

Questions & Answers

How can I add a custom validation message for banned users in this Laravel 8 application?

I am working on a blogging application in Laravel 8.

There are 4 user roles, among which, the "Super-admin". The super admin can ban all users that are not Super-admins.

enter image description here

The banning happens as follows:

In the users table, there is an active column of type tinyint.

In the UserRightsController controller I have this small function that does the banning:

public function ban_user($id){
      User::find($id)->update(['active' => 0]);
      return redirect()->back()->with('success', 'The user is now banned');
}

Once a user is banned, she/he will be unable to login. I have achieved this by going to vendor\laravel\ui\auth-backend\AuthenticatesUsers.php and changing this:

protected function credentials(Request $request)
{
    return $request->only($this->username(), 'password');
}

to

protected function credentials(Request $request)
{
    return array_merge($request->only($this->username(), 'password'), ['active' => 1]);
}

The problem:

Any attempt by a banned user to sign in fails, but the error message is still the default one:

These credentials do not match our records.

enter image description here

EDIT:

In app\Http\Controllers\Auth\LoginController.php, I have overwritten the credentials from AuthenticatesUsers.php:

protected function credentials(Request $request)
 {
   return array_merge($request->only($this->username(), 'password'), ['active' => 1]);
 }

But the issue of a specific message remains :(

Questions:

  1. How do I add a custom message like: "Your account was suspended"?
  2. Is there a better alternative to using return array_merge($request->only($this->username(), 'password'), ['active' => 1]) in AuthenticatesUsers.php?
Comments:
2023-01-07 20:30:39
You should be able to overwrite the sendFailedLoginResponse() and probably also overwrite the login() function...
2023-01-07 20:30:39
Wow, you really change code in vedor? Btw, use middleware to check active status and redirect with message if user is banned
2023-01-07 20:30:39
@Maksim One of the questions is if there is a better alternative to changing the code in the vendor directory, the way I did. You can provide an alternative in your answer, :)
2023-01-07 20:30:39
Yes, as i said - use middleware - you can read about this here. Or make custom auth guard, but this is overenginering. laravel.com/docs/9.x/middleware
2023-01-07 20:30:39
The normal way to do this is either create a middleware or to overwrite the logic of your LoginController. This controller uses the AuthenticatesUsers Trait. You should never overwrite code in your vendor folder directly...
2023-01-07 20:30:39
@Aless55 There already is an auth middleware in the application, since I scaffolded the out-of-the-box authentication Laravel 8 comes with. I wish I knew how to change it. Instead of changing the AuthenticatesUsers.php file.
Answers(0) :