Search code examples
laravelvalidationunique

Laravel Unique validations to ignore validation if the user is different


I have master skills table, and separate skill table for student. Each students to add their skills to their resume through the master skill table.

Now, the same skill should not be added again and again to the stu_resume_skills table by student, I have the Laravel unique validations for user. But this validation is not allowing different user even though they don't have any skill in their resume.

Master Skill Table - jobs_masterskills - (id, skillname),

Student Skill Table - stu_resume_skills - (id, user_id, skill_id)

public function SkillsAddFormValue(Request $request)
{
    request()->validate([
        'skill_id' => 'required|skill_id|unique:stu_resume_skills',
    ]);

    $save = new StudentSkillsModel;
    $save->user_id = Auth::user()->id;
    $save->skill_id = $request->skill_id;
    $save->expertise_level = $request->expertise_level;

    $save->save();

    return redirect('student/academics/resume/skills/skills-list');
}

Table

I tried writing the unique validation for it is not working.


Solution

  • It appears you are trying to create unique skills for every user, but you are checking them in the whole stu_resume_skills table, so you need a validation for each user individually

    This might work for you

    public function SkillsAddFormValue(Request $request)
    {
        request()->validate([
            'skill_id'     => [
                'required',
                'exists:jobs_masterskills,id',
                Rule::unique('stu_resume_skills')->where(function ($query) {
                    return $query->where('user_id', Auth::user()->id);
                })
            ],
        ]);
    }
    

    namespace - use Illuminate\Validation\Rule;