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

nickdavies07's avatar

Help with middleware to check `user` access to `asset` based on access to `school`

I've recently started learning Laravel and I'm trying to piece together a basic Asset Management System.

I have three tables - Users, Schools and Assets.

Users->Schools is many to many relationship. Schools->Assets is One to Many.

I have assets set up to be displayed through the assets/{asset} view. i.e. assets/1 asset/3 etc calls show() method in AssetController.

I'm trying to set up a middleware class that will check if the current logged in user is allowed to access the asset, depending on whether they can access that particular school the asset is assigned to.

Is there an easy way of doing this?

My tables are:

Users:

| id | name | email | | ------------- | ------------- | ------------- | | 1 | nick | [email protected] | | 2 | ted | test2@test.com | | ... | ... | ... |

Schools:

| id | name | | ------------- | ------------- | | 1 | School A | | 2 | School B | | ... | ... |

School_User:

| id | school_id | user_id | | ------------- | ------------- | ------------- | | 1 | 1 | 1 | | 2 | 2 | 1 | | 3 | 2 | 2 | | 4 | 2 | 3 | | 5 | 3 | 1 | | 6 | 3 | 2 |

Assets:

| id | name | | ------------- | ------------- | | 1 | Asset A | | 2 | Asset B | | 3 | Asset C | | ... | ... |

0 likes
3 replies
Vilfago's avatar

You can retrieve all users of one school from the Asset. So something like that should work.

//I guess that the relation from asset to school named "school()" and from school to users named "users()"
$asset_with_user = Asset::with('school.users')->findOrFail($asset_id);

//and then, you check that your user is in the allowed_users
if($asset_with_user->school->users->pluck('id')->search($request->user()->id)
{
    //Authorized
}
martinbean's avatar
Level 80

@nickdavies07 http://laravel.com/docs/master/authorization

Create a school policy that determines whether a user belongs to that school, and another policy for checking access to individual assets.

class SchoolAssetController extends Controller
{
    public function __construct()
    {
        // Check user can view school for every request
        $this->middleware('can:view,school');

        // Individual asset checks
        $this->authorizeResource(Asset::class);
    }
}
1 like

Please or to participate in this conversation.