Laravel-如何验证公司id的唯一部门名称

Laravel-如何验证公司id的唯一部门名称,laravel,Laravel,在我的Laravel-8工作门户应用程序中,我有以下四(4)个表(模型): 部门、用户、公司和公司档案 用户只能在具有唯一电子邮件的用户表上出现一次。但他可以拥有多个公司档案,因为他可以远程为多个公司工作: 这些是模型: class Department extends Model { protected $table = 'departments'; protected $primaryKey = 'id'; protected $fillable = [

在我的Laravel-8工作门户应用程序中,我有以下四(4)个表(模型):

部门、用户、公司和公司档案

用户只能在具有唯一电子邮件的用户表上出现一次。但他可以拥有多个公司档案,因为他可以远程为多个公司工作:

这些是模型:

class Department extends Model
{
    protected $table = 'departments';
    protected $primaryKey = 'id';
    protected $fillable = [
                'id',
                'company_id',
                'name',
            ];

    public function company()
    {
        return $this->belongsTo('App\Models\Company','company_id');
    }
}

class Company extends Model
{    
     protected $table = 'companies';
     protected $primaryKey = 'id';
     protected $fillable = [
                'id',
                'name',
                'org_image',
             ];

    public function users()
    {
        return $this->hasMany('App\Models\User');
    }

    public function departments()
    {
     return $this->hasMany('App\Models\Department');
    }
}

class User extends Authenticatable
{
    protected $hidden = [
        'password',
        'remember_token',
    ];
    
    protected $fillable = [
        'name', 
        'first_name',
        'other_name',
        'last_name',
        'username',
        'email', 
        'password', 
    ];

    public function profile(){
        return $this->hasMany('App\Models\CompanyProfile', 'employee_id');
    }

    public function company(){
        return $this->hasMany('App\Models\CompanyProfile', 'company_id');
    }
}

class CompanyProfile extends Model
{    
     protected $table = 'company_profiles';
     protected $primaryKey = 'id';
     protected $fillable = [
                'id',
                'user_id',
                'company_id',
                'department_id',
                'employment_date',
            ];
}
我为该部门提供了以下请求规则验证:

public function rules()
{
    return [
        'name' => [
            'required',
            'string',
            'min:2',
            'max:100',
        ],

        'company_id' => [
            'required',
        ],

    ];
}
如何在申请规则中验证部门名称与公司id的唯一性


谢谢

您可以使用$this关键字=>
$this->company\u id
访问公司id,请遵循下面的规则功能

使用\验证\规则

public function rules()
{
    return [
            'name' =>  [
                         'required',
                         'string',
                         'min:2',
                         'max:100',
                          Rule::unique('departments')
                                ->where('company_id', $this->company_id)
                        ]
        ];
}

public function messages()
{
    return [
        'name.unique' => 'Department name and company_id has to be unique.',
    ];
}