How to lessen redundant line of code? (php)

134 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

You can use a laravel-middleware instead of the policy, to apply for specific methods inside your __construct():

php artisan make:middleware OperatorMiddleware

Do some filter inside the handle methods.

class OperatorMiddleware
{
    public function handle($request, Closure $next, $guard = null)
    {
        //do some filter here

        return $next($request);
    }
}

Inside the \Http\Kernel.php, register the middleware inside the routeMiddleware.

protected $routeMiddleware = [
    'operator' => \App\Http\Middleware\OperatorMiddleware::class,
],

And you can call it for specific method(s):

public function __construct()
{
    $this->middleware('operator', ['only' => ['apply','cancel']]);
}