Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

khanimranm's avatar

How to do Login authentication with many to many relationship table field.

3 Tables

  1. users
  2. groups
  3. group_user - The many to many relationship table.

My Login view has email, password, and an optional group ID for login.

Authentical depends on user input.

  1. When a user enters email and password only, the regular authentication.
  2. When a user enters email, password and the optional group id , then authentication on these 3 input.

How to authenticate in many to many relationship? Please help.

0 likes
1 reply
morteza's avatar
morteza
Best Answer
Level 12

Add use hash to LoginController:

use Illuminate\Support\Facades\Hash;

Overwrite login method in your LoginController:

public function login(Request $request)
    {
        $this->validate([
        'email' => 'required|string',
        'password' => 'required|string',
                'group_id' => 'nullable|integer',    
        ]);

       
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }
    if ($request->group_id) {
        $group = Group::find($request->group_id);
        $user = $group->users()->where('email', $request->email)->first();
                if ($user && Hash::check($request->password, $hashedPassword)) {
            return $this->sendLoginResponse($request);  
        }
    } else if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);  
        }
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

Please or to participate in this conversation.