I am using laravel 5.2 and I am getting this error while creating user.
Call to undefined method Illuminate\Database\Query\Builder::associate()
this is my User.php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password', 'role_id'
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->hasOne('App\Role');
}
}
my role.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $table = "roles";
protected $fillable = [
'name','description'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
and this is migration I used
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles');
$table->rememberToken();
$table->timestamps();
});
}
this is controller code I am using
$role = Role::find(1);
$user = new User();
$user->name = "Admin";
$user->email = "email@gmail.com";
$user->password = bcrypt("password");
$user->role()->associate($role);
$user->save();
when I run this code I get "Call to undefined method Illuminate\Database\Query\Builder::associate()" error
let me know what is wrong with my code.