Monday, April 10, 2017

laravel load candidates with given skills

So in my website users can create candidates (one-many relation) and those candidates can have skills (many-many).

User model:

public function candidates() {
    return $this->hasMany(Candidate::class);
}

candidate model:

 public function skills() {
    return $this->belongsToMany(Skill::class, 'candidate_skill', 'candidate_id', 'skill_id');
}

Skills model:

public function candidates() {
    return $this->belongsToMany(Candidate::class, 'candidate_skill', 'candidate_id', 'skill_id')
        ->withTimestamps();
}

I already have an index page where an user can view ALL his made candidates

$candidates = Auth::user()->candidates;

on the edit page, skills can get synced to the candidate in question

  $candidate->skills()->sync(request()->skills);

and back to the index page it shows how many skills the candidates have

<td></td>

now, I need to make a search bar. My table already has one(dataTable) to search in the already loaded td's. But I need a search bar to search for candidates which have certain skills, say I want to search for candidates which are synced with 'css' and only show those in the table.

I read through the laravel docs and tried eager loading it:

$hasCss = $candidates->load(['skills' => function ($query) {
        $query->where('name', '=',  'css');
    }]);

but this just loaded all candidates with only the css skill displayed, even the candidates who dont have it. I want to only load candidates who have the skill and leave the others out.

How do I do this, I'm clueless :s



via Thomas96

Advertisement