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

zoidq's avatar
Level 7

Multiple Eloquent Relationships using "with"

Howdy!

So I've been struggling with something that I think should be relatively simple for a while and thought I'd give the pros at Laracast a shout to see if anyone could put me out of my mystery.

The application I'm building has multiple "apps" aka (sections or tools). Depending on which user is logged in, I may want to give them access to only certain apps rather than the whole toolset. Furthermore I may want to give them specific access, i.e view/edit/delete however that part doesn't really add any complexity.

So far I have three tables, they look like this:

Users: (standard laravel table) id | name | email | etc

apps: id | name | description | link

app_permissions: id | app_id | user_id | read | write | delete

I would like to be able to user the user_id to find out if the user can read/write/delete a specific app.

I know which app the user is trying to access based on the current URI cross referenced with the apps:link column.

Doing this with a direct database query and joins seems easy but it doesn't feel like the laravel way and I'd like to learn something new and achieve this with relationships.

This is what I currently have: $access = DB::table('apps') ->leftJoin('app_permissions', 'app_permissions.app_id', 'apps.id') ->where('apps.link', $request->segment(1)) ->where('app_permissions.user_id', Auth::id()) ->select('app_permissions.level', 'apps.id', 'app_permissions.read', 'app_permissions.write', 'app_permissions.delete') ->get()->first();

How could I achieve the same thing with eloquent relationships?

0 likes
2 replies
zoidq's avatar
Level 7

@WILBURPOWERY - You rock!

Thanks for sharing hasManyThrough, I didn't know about this.

1 like

Please or to participate in this conversation.