Search code examples
phplaravellaravel-authorizationlaravel-authentication

Laravel Auth Check For An Organization


when a user tries to register I require them to enter an organization ID, I want that organization ID to be checked against my Organization table and see if it exists. If it exists then register the user and if it fails then return an error message. I've been looking around online and couldn't personally find anything like this. If anybody could help, I'd greatly appreciate it.

I am using Laravel 5.6 with the default auth.

Validator:

return Validator::make($data, [
    'first_name' => 'required|string|max:255',
    'last_name' => 'required|string|max:255',
    'org_id' => 'required|string|max:16',
    'email' => 'required|string|email|max:255|unique:users',
    'password' => 'required|string|min:6|confirmed',
]);

User Create:

 return User::create([
                'first_name' => $data['first_name'],
                'last_name' => $data['last_name'],
                'org_id' => $data['org_id'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
                'is_active' => 1
            ]);

Solution

  • You're looking for the exists rule of Laravel's Validation:

    'org_id' => 'required|string|max:16|exists:organizations,id',
    

    The rule is essentially

    exists:{table},{column?}
    

    Where table is required, and column is optional, generally used if the name (in this case org_id) is different from the column you want to compare.

    For full details, check the Documentation.