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.)
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 ?
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
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community