Support the ongoing development of Laravel.io →
Security Requests
Last updated 1 year ago.
0

Unfortunately, Laravel doesn't have anything built-in that will help you with this, but you can specify your own custom filter.

First, create a filter:

Route::filter('department', function ($route, $request) {
    // Check to see if the current user belongs to the department:
    $department_id = $request->segment(1);
    if (!Auth::user()->canAccessDepartment($department_id)) {
        // The user shouldn't be allowed to access the department! Redirect them
        return Redirect::to('/url/to/notice/here');
    }
});

You can use the Request::segment() method to get the Department ID from the URL. Replace canAccessDepartment with whatever logic you've actually defined.

Then apply the filter to the route(s):

Route::group(array('before' => 'department'), function () {
    Route::resource('department','DepartmentsController');
    Route::resource('department.project','ProjectsController');
});

(For help with this, check out the route filters section of the docs.)

Last updated 1 year ago.
0

Thank you, this sounds easy (now) :) .

One question left:

canAccessDepartment()

this method would need to be defined in User model or should be defined in filters.php ?

Last updated 1 year ago.
0

RokSiEu said: this method would need to be defined in User model or should be defined in filters.php ?

In my example, it would be defined in the User model. That's really your choice though. You basically just need to create some logic somewhere that determines whether a User is allowed to access a Department. You could even do it in the filter (but it's a good idea to keep that logic elsewhere):

if ($user->departments()->where('id', $department_id)->count() < 1) {
    // The user is not authorized
}
Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

RokSiEu roksieu Joined 31 Jan 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.