Laravel 5 belongsToMany() on custom table

I’m using custom made tables. It is simple user role feature. But not using conventional Eloquent database schema style.

Table User

  1. userId(PK)
  2. userName (varchar)

Table Role

  1. roleId (PK)
  2. roleName (varchar)

Table userrole pivot column

  1. userroleId
  2. roleId
  3. userId

Now I’ve Model User which has this method

    public function roles()
{
    return $this->belongsToMany("AppRole", "userrole", "roleId", "userId");
}

When I make call like this it gives error

$roles = AppUser::where("userId", "1")->first()->roles;
dd($roles);

Error it displays is:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'role.id' in 'on clause' (SQL: select `role`.*, `userrole`.`roleId` as `pivot_roleId`, `userrole`.`userId` as `pivot_userId` from `role` inner join `userrole` on `role`.`id` = `userrole`.`userId` where `userrole`.`roleId` is null)

Here’s my humble request. Please don’t suggest to change the table schema. I can’t. I’m stuck with this. Thank you!

Answer

Have you set the primary key on your “userrole” model?

Laravel automatically assume that you’re primary key is named id.

See this: http://laravel.com/docs/5.1/eloquent

Take a look at the primary key section:

Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention.

Try to override it at your userrole model like so:

protected $primaryKey = 'roleId';

Try to read all the doccumentattion carefully.