FareedR's avatar

Can someone show me the correct way to fix this relationship

// Database
users
id  |   name
1       John 

// Database
user_skills
user_id |   skill_id
1           1
1           2

//Database
skills
id  |   skill_name
1       Java
2       Laravel


// User.php
 public function hasUserSkill()
    {
        return $this->hasMany('App\UserSkill');
    }
// Skill.php
public function userSkill()
    {
        return $this->hasMany('App\UserSkill');
    }
//UserSkill.php
public function users()
    {
        return $this->belongsToMany('App\User');
    }

    public function skills()
    {
        return $this->hasMany('App\Skill');
    }

am I right ?

0 likes
2 replies
lostdreamer_nl's avatar

This is not necessary (you have 1 model too many)

Here's a revised version (with also different naming):

// User.php
 public function skills() {
    return $this->belongsToMany('App\Skill');
}


// Skill.php
 public function users() {
    return $this->belongsToMany('App\User');
}

// usage:
$user = User::create([
   'name' => 'test',
]);

$php = Skill::create([
    'name' => 'php'
]);

$html = Skill::create([
    'name' => 'html'
]);

$user->attach($php);
$user->attach($html);

// or  $user->sync([$php->id, $html->id]);

$user = User::with('skills')->where('name', 'test')->first();
dd($user->toArray());

I would also name the 'skill_name' on the Skill model 'name'

I hate seeing things like : $user->user_name, $skill->skill_name if it's no more informative then $user->name and $skill->name

Please or to participate in this conversation.