Courses

Laravel API Code Review and Refactor

Using Gates Properly: Remove isAble() Method

You're reading a FREE PREVIEW of a PREMIUM course.

Link to the repository

[Only for premium members]

The next thing I don't like is a specific ->isAble() method instead of using Laravel default Gates/Policies:

app/Http/Controllers/Api/V1/OrderController.php

public function show(Order $order)
{
$this->isAble('view', $order); // policy
 
// ...
}
 
public function update(UpdateOrderRequest $request, Order $order)
{
try {
$this->isAble('update', $order);
 
// ...

This method comes from the base ApiController and looks like this:

app/Http/Controllers/Api/V1/ApiController.php

class ApiController extends Controller
{
protected $policyClass;
 
public function isAble($ability, $model)
{
return Gate::authorize($ability, [$model, $this->policyClass]);
}

I've been honestly trying to understand the purpose of this extra layer. Maybe I'm wrong here, but I don't see its benefit over just calling Gate::authorize() directly from Controllers.

So, this is my refactored "Laravel way" version...

The full lesson is only for Premium Members.
Want to access all 15 lessons of this course? (56 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord