Nitish Kumar
Nitish Kumar

Reputation: 6276

Laravel many to many relationship error

I'm having two models under the name of Plugins and User with tables respectively. I'm trying to have many to many relationship with a pivot table named plugin_user in the migration named create_users_plugins_table.php.

Following is the schema:

public function up()
{
    Schema::create('plugin_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('plugins_id');
        $table->json('contents');
        $table->timestamps();
    });
}

In the User model I've following function for relationship:

public function userplugins(){

    return $this->belongsToMany('App\Plugins')->withPivot('contents');
}

While fetching the row by following code:

$user = User::findorFail($id);
return $user->userplugins()->first()->contents;

I'm getting an following error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'nitsbuilder.plugins_user' doesn't exist (SQL: select plugins.*, plugins_user.user_id as pivot_user_id, plugins_user.plugins_id as pivot_plugins_id, plugins_user.contents as pivot_contents from plugins inner join plugins_user on plugins.id = plugins_user.plugins_id where plugins_user.user_id = 1 limit 1)

Please help me out in fixing this bug.

Thanks

Upvotes: 0

Views: 623

Answers (2)

Frnak
Frnak

Reputation: 6802

The problem is the name of your table. The error says it was looking for plugins_user but your migration shows plugin_user table which is missing the s. This might be due to the naming of the model Plugins which should be Plugin

Either change the table name or go to https://laravel.com/docs/5.1/eloquent-relationships#many-to-many to check how to change the referenced table of the relation.

Upvotes: 1

Ariful Haque
Ariful Haque

Reputation: 3750

Looks like in your Migration, your table name is

`plugin_user` 

but the query searching for

`plugins_user`

You might need to update your Plugin model with the table name.

Upvotes: 1

Related Questions