3 years ago

Eloquent nested relations with whereHas clause

Posted 3 years ago by kriolo_developer

Hello Guys,

I have the following relations structure: cabinets > drawers > folders > documents.

I want to get only the documents that the user has rights (roles) to access. And I need the whole structure (cabinet > drawer > folder > document)

Here is my code:

$user = Auth::user();
$roles = $user->roles->pluck('id')->toArray();

$data = Cabinet::whereHas('drawers.folders.documents.roles')->with(['drawers.folders.documents.versions' => function($query) {
        $query->where('current_version', true);
    }, 'drawers.folders.documents.roles' => function($query) use ($roles) {
        $query->whereIn('', $roles);

    return response()->json(['data' => $data]);

This kinda works, but the problem is I still get documents that have "roles: []", or documents that simply don't have any roles associated with them (empty relation).

I want to prevent this type of documents in my final result, where I don't want documents with am empty roles[] to get included in the the final result.:

id: 274,
name: "test",
description: "test",
other_details: "a test document",
document_type_id: 4,
folder_id: 46,
deleted_at: null,
versions: [...],
roles: [ ]

Thank you in advance.

Please sign in or create an account to participate in this conversation.