Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

maj's avatar
Level 1

Many to many relationship not working. Can anyone help?

Hello i have been trying to create a many to many relationship. but it does not work.

I have 2 models User and Competency and 2 tables Users and Competenties

First i created a migration for the pivot table:

    public function up()
    {
        Schema::create('competency_user', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('competency_id')->unsigned();
            $table->foreign('competency_id')->references('id')->on('competencies');

            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

Than i added the BelongsToMany to the classes:

class User extends Authenticatable
{
    use HasApiTokens, Notifiable, SoftDeletes;

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'is_admin' => 'bool',
        'is_super_admin' => 'bool'
    ];

    protected $fillable = [
        'name', 'email', 'password', 'team_id'
    ];

    protected $hidden = [
        'password', 'remember_token', 'is_admin', 'is_super_admin'
    ];
    
.....

.....

    public function competencies()
    {
        return $this->belongsToMany(Competency::class,'competency_user','competency_id','user_id');
    }

class Competency extends Model
{
    use SoftDeletes;
        
    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected $fillable = [
        'name', 'description', 'icon', 'competency_set_id', 'card_image_da_id', 'order_value'
    ];

...

...

      public function Users()
    {
        return $this->belongsToMany(User::class,'competency_user','user_id','competency_id');
    }
}

But when i test i out i get null or not an error at all:

        $user = User::find(1);
        dd($user->competencies()->toSql());
]8;;file:///Users/maj/Documents/code/sites/api/tests/Feature/ClientUpdateProfileTest.php#L133\^]8;;\ "select * from `competencies` inner join `competency_user` on `competencies`.`id` = `competency_user`.`user_id` where `competency_user`.`competency_id` = ? and `competencies`.`deleted_at` is null"

this should be something like (this works in the database)

SELECT * 
FROM `competencies` c
INNER JOIN `competency_user` cu ON c.`id` = cu.`competency_id`
INNER JOIN `users` u ON cu.`user_id` = u.`id`
        $user = User::find(1);
        dd($user->competencies()->attach(4));

give null

can anyone help me out?

0 likes
19 replies
maj's avatar
Level 1

ow and i'm running laravel 5.7.29 and php 7.2

Sinnbeck's avatar

What do you get if you run this

$user = User::with('competencies')->find(1);
$dd($user->competencies);
1 like
maj's avatar
Level 1

oke this is a problem....

Illuminate\Database\Eloquent\RelationNotFoundException : Call to undefined relationship [compencies] on model [App\User].
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:34
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:586
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:90
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:588
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:556
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:536
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:504
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php:77
 /Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:329
 /Users/maj/Documents/code/sites/api/tests/Feature/ClientUpdateProfileTest.php:132
Sinnbeck's avatar

No it is my spellchecker that's bad :)

competencies not compencies

Updated

maj's avatar
Level 1

Should have seen that .. copy past from the internet always a good idea...

response



]8;;file:///Users/maj/Documents/code/sites/api/tests/Feature/ClientUpdateProfileTest.php#L133\^]8;;\ Illuminate\Database\Eloquent\Collection]8;;file:///Users/maj/Documents/code/sites/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php#L13\^]8;;\ {#1220
  #items: []
}
Process finished with exit code 1

there should be 2 items linked

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

It seems you have your column names reversed

public function competencies()
    {
        return $this->belongsToMany(Competency::class,'competency_user','user_id','competency_id');
    }
1 like
maj's avatar
Level 1

You are right. I know i tested that at some point in time. thank you

it works now! At least getting things. now setting ..

maj's avatar
Level 1

the attatch doenst work..

        $user = User::find(1);
        $user->competencies()->attach([5]);

should work right?

Sinnbeck's avatar

Yes. Did you change both methods?

public function users()
    {
        return $this->belongsToMany(User::class,'competency_user','competency_id', 'user_id');
    }

And do you get any errors or such from the attach method? Or do you just not see anything show up in the database

A Last, is there a competency row with id 5?

maj's avatar
Level 1

yes i changed (swaped) them

user 
    public function competencies()
    {
        return $this->belongsToMany(Competency::class,'competency_user','user_id','competency_id');
    }
Competency
    public function Users()
    {
       return $this->belongsToMany(User::class,'competency_user','competency_id','user_id');
    }

no no erros i runs but the db does not change

yes there is a competency with id 5

Sinnbeck's avatar

Hmm that is strange. Do you have either clockwork or debugbar installed? If not install one of them (I prefer clockwork myself), and check the database tab. Does the full queries look right (much more precise than toSql())

maj's avatar
Level 1

I don't have either one... but ->tosql fails null

Error : Call to a member function toSql() on null

maj's avatar
Level 1

thnx installing it now

maj's avatar
Level 1

got it ;) how to use it?

maj's avatar
Level 1

never mind restart the server it works thanks

an clockwork seems nice!

anyway thanks a lot!!!!!!

maj's avatar
Level 1

thnx ill play around with it first i commit this many to many relation ;)

Please or to participate in this conversation.