Level 102
Something like this you mean?
return view('admin.users.index',['users'=> User::whereHas('role', function($query) {
$query->where('name', 'admin');
})->orderBy('name')->paginate(10)]);
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a users table with many to many relationship with a roles table. And I have a user_role table which saves roles that are assigned to the user. The question is, is there a way to paginate users that have a specific role? I
Here is my index function in my resource controller:
public function index()
{
if(Gate::denies('logged-in')){
dd('no access allowed');
}
if(Gate::allows('is-admin')){
return view('admin.users.index',['users'=> User::paginate(10)]);
}
dd('you need to be an admin');
}
And this is admin.users.index:
@extends('template.main')
@section('content')
<div class="row">
<div class ="col-12">
<h1> Pending Enrolment Applications</h1>
<a class="btn btn-sm btn-success float-end" href="{{route('admin.users.create') }}" role="button">Create New Admin Account</a>
</div>
</div>
<div class= "card">
<table class="table">
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Middle Name</th>
<th scope="col">Last Name</th>
<th scope="col">LRN</th>
<th scope="col">PSA/Birth Certificate/NSO</th>
<th scope="col">Form 138</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<th scope="row">{{$user ->name}}</th>
<td>{{$user ->middlename}}</td>
<td>{{$user ->lastname}}</td>
<td></td>
<td></td>
<td></td>
<td>
<form action="{{route('admin.users.destroy',$user->id) }}" method ="POST" >
@method("DELETE")
@csrf
<a class="btn btn-sm btn-primary" href="{{route('admin.users.show',$user->id) }}" role="button">View</a>
<a class="btn btn-sm btn-success" href="{{route('admin.users.edit',$user->id) }}" role="button">Accept</a>
<button type="submit" class="btn btn-sm btn-danger">
Delete
</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
{{$users->links()}}
</div>
@endsection
Something like this you mean?
return view('admin.users.index',['users'=> User::whereHas('role', function($query) {
$query->where('name', 'admin');
})->orderBy('name')->paginate(10)]);
Please or to participate in this conversation.