I get this error in my view when i tried to check whether the user has some role. The exact error is Call to undefined method Illuminate\Database\Query\Builder::role() (View: C:\xampp\htdocs\laravel-projects\acl\resources\views\admin.blade.php
Here is the admin.blade.php code
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td><input type="checkbox" {{ $user->hasRole('User') ? 'checked' : '' }} name="role_user"></td>
<td><input type="checkbox" {{ $user->hasRole('Author') ? 'checked' : '' }} name="role_author"></td>
<td><input type="checkbox" {{ $user->hasRole('Admin') ? 'checked' : '' }} name="role_admin"></td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
</tr>
@endforeach
hasRole() is a function in the user model. But from the error it throws undefined methode role(). But there is no method called role()
Here is my controller
class AdminController extends Controller
{
public function index()
{
$user_details = User::all();
return view('admin')->with('users' , $user_details);
}
}
I also did include the method while getting the data from DB like
$user_details = User::with('hasRole')->get();
Even this didn't work.
This is my User model.
<?php
namespace App;
use App\Role;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function roles()
{
return $this->belongsToMany('App\Role','user_role','user_id','role_id');
}
public function hasAnyRole($roles)
{
if(is_array($roles)){
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
}
else{
if ($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role)
{
if ($this->role()->where('name',$role)->first()) {
return true;
}
return false;
}
}