You can use the hasManyThrough relationship.
https://laravel.com/docs/master/eloquent-relationships#has-many-through
Basically a user can have many apps, but through the relationship specified in the app_permissions table.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
Please or to participate in this conversation.