I'm basically new to Laravel. I keep getting this "Call to member function roles() on array" error.
I'm trying to add a user's role into my database which has many to many relation. I've looked for an answer for this everywhere and the results said I just needed to add a return statement in my function. But I already have a return statement and it still doesn't work.
So here are my codes.
User.php model
<?php
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
protected $primaryKey = 'user_id';
protected $fillable = [
'user_fname', 'user_mname', 'user_lname', 'user_ptitle', 'user_sex', 'user_civilstatus', 'user_nationality', 'user_bday', 'user_bplace', 'user_address', 'user_mobile', 'user_landline'
];
protected $hidden = [
'password', 'remember_token',
];
public function login(){
return $this->hasOne('App\Login', 'user_id');
}
public function registercoop(){
return $this->hasOne('App\CoopDetails', 'coop_id');
}
public function listcomaker(){
return $this->hasMany('App\LoanCoMaker', 'user_id');
}
public function roles(){
return $this->hasMany('App\Role', 'role_users', 'user_id', 'role_id');
}
}
Role.php model
<?php
class Role extends Model
{
public function users(){
return $this->belongsToMany('App\User','role_users', 'role_id', 'user_id');
}
}
Lines from my AccountController.php where the saving to database happens
$user=[
'user_email' => $email,
'password' => $password
];
$count = DB::table('users')
->where('created_at', '>=', 'CURRENT_DATE')
->count(); //Count entries for that day.
$year = Carbon::now()->year;
$month = Carbon::now()->month;
if ($count<100 && $count>10){
$count="0".$count;
$user_id = $year.$month.$count;
}
else if ($count<10){
$count="00".$count;
$user_id = $year.$month.$count;
}
else{
$user_id = $year.$month.$count;
}
$user->roles()->attach($user_superadmin);
P.S I actually have made it work the first time. I just renamed my old model UserType.php into Role.php, updated my migrations, seeders, controllers, models, etc. and then it stopped working properly.
Can someone help me point out what am I doing wrong?