I'm building my first API in Laravel, where I used Passportand now I need to be able to change the response by role which was implemented using spatie/laravel-permission.
class JobsController extends Controller
{
public function index()
{
$jobs = Job::with('company')->get();
return response()->json($jobs);
}
}
class CompaniesController extends Controller
{
public function index()
{
$companies = Company::all();
return response()->json($companies);
}
}
In the above examples, I need the admins to be able to see every record, and the employees to just see the jobs and the companies that they are assigned.
You can conditionally add query scopes using the when or unless builder methods, e.g.
public function index()
{
$companies = Company::unless(auth()->user()->hasRole('admin'), function (Builder $builder) {
$builder->where('user_id', auth()->id();
})->get();
}
So, this will scope the query to the current user unless they are an admin. You can mix and match the use of these methods to suit different circumstances.