My controller is already working and complete. But I observe redundant/repetition of the code.
Specifically for the code below:
$this->authorize('applicant', $job);
Here's the entire code in my controller:
public function interviewees(Job $job)
{
//more codes
}
public function applicants(Job $job)
{
//more codes
}
public function apply(Job $job)
{
$this->authorize('applicant', $job);
//more codes
}
public function cancel(Job $job)
{
$this->authorize('applicant', $job);
//more codes
}
//and 5 more methods using same code of $this->authorize('applicant', $job);
My question is there a way in php or in laravel we can handle this situation, lessen redundant codes?
You can use a laravel-middleware instead of the policy, to apply for specific methods inside your
__construct():Do some filter inside the handle methods.
Inside the
\Http\Kernel.php, register the middleware inside therouteMiddleware.And you can call it for specific method(s):