Home » Php » php – Laravel 5.5 unique validation rule on seperate table with different column name

php – Laravel 5.5 unique validation rule on seperate table with different column name

Posted by: admin July 12, 2020 Leave a comment

Questions:

So I have users and companies. A user belongs to one company.

I want to validate a user registration so that the business_name field they use to register is unique in the companies table, the goal is to not allow users from creating duplicate companies.

Here is my register function:

public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'business_name' => 'required|unique:companies',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6',
        ]);


        if ($validator->fails()) {
            return response()->json(['error'=>$validator->messages()], 401);
        }

}

The field I want to compare against is the companies.name to check for uniqueness.

Is this possible? At the moment it is trying to look for business_name in the companies table.

How to&Answers:

Never mind, managed to figure it out. Just needed an extra parameter to specify the column name:

'business_name' => 'required|unique:companies,name',