Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Conixs's avatar

Change API response based on role?

Hello Everyone,

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.

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

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.

Please or to participate in this conversation.