Search code examples
laravellaravel-resource

Laravel api resource only if its owned by user


Lets say a user belongs to a company and each company has many projects. Now I wanna make an API resource for projects. For this, I wanna work with https://laravel.com/docs/6.x/eloquent-resources

For example for the show method of the controller, I could do it with laravel route model binding like so:

class ProjectController extends Controller {
    public function show(Project $project) {
        return new ProjectResource($project);
    }
}

This works as expected. But of course, the user (identified by a token - this is already working) should only see/list/update/delete projects from his company he belongs to.

Now I could forget about route model binding and do it manually like so:

    public function show($id, Request $request) {
        $project = Project::query()
            ->where("id", $id)
            ->whereHas("company",function ($query) use ($request) {
                $query->where('id', $request->user()->company_id);
            })
            ->first();

        return $project ? new ProjectResource($project) : Route::respondWithRoute('api.fallback.404');
    }

But is this they way to go? It looks like a dublication of code to implement this for all other resources (offices, customers, etc. which all belongs to a company) in the same way?

I could of course make it a bit nicer, with local scopes, but not sure if there aren't better ways?


Solution

  • Use Policies and can middleware. For viewany scenario i suggest to consider global scopes. If your application should filter Project most of the times, then global scope should solve the problem.