Reputation: 878
I'm looking for a fix to allow a redirect in a sub-function call, instead of in a controller
I've created the following function & call and it works, with the redirect in the controller instead of my sub function call.
Here is my call to the function checkAccess():
$access = new \App\Library\Access;
if($access->checkAccess($accessList, 'admin-dashboard', 'r')){
return view('portal.admin.dashboard');
}else{
return redirect('/');
}
Here is my function:
public function checkAccess($accessList, $name, $permission){
return array_filter($accessList, function($element) use($name, $permission){
if($element->name == $name && $element->permission == $permission){
return true;
}else{
return false;
}
});
}
I have tried replacing the return false; with the redirect and this does not work. It basically just returns true.
Upvotes: 0
Views: 1071
Reputation: 13457
I'm looking for a fix to allow a redirect in a sub-function call, instead of in a controller
Don't. Your access-checking service should have zero knowledge of the view layer (controllers, views, redirects, etc.). If you've ever heard of concepts such as separation of concerns and the single responsibility principle, that type of blending is exactly what these concepts encourage you to evaluate and separate properly.
Your Access
class is meant to check for access levels, permissions, etc. It should not be meant to generate responses based on those things. That's the controller's job.
Your first code example is perfectly fine, and is what I'd recommend you stick with.
Upvotes: 1
Reputation: 15382
If I understand your issue, you want something like this
public function checkAccess($accessList, $element, $permission){
if (is_array($accessList)) {
foreach ($accessList as $access) {
if ($access->element == $element && $access->permission == $permission) {
return view('portal.admin.dashboard');
}
}
}
return redirect('/');
}
and then, you should return
the result
$access = new \App\Library\Access;
return $access->checkAccess($accessList, 'admin-dashboard', 'r');
Concerning the better way of checking if an object list has parameters, maybe you find useful the in_array
function of php.
Upvotes: 0