🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Authorization with Gates

A gate is a rule that says if a user may do one action. It answers yes or no for one user and one thing.

Asking a gate

Ana is the owner, so the gate says yes.

// Ana asks about her own task
if (Gate::allows('edit-task', $task)) {
    return 'Allowed';
}

return response('Not allowed', 403);

A gate says no

Ben is not the owner, so the gate says no.

// Ben asks about Ana's task
if (Gate::allows('edit-task', $task)) {
    return 'Allowed';
}

return response('Not allowed', 403);

A gate about the user alone

A gate can also check a fact about the user alone.

if (Gate::allows('manage-users')) {
    return 'Admin area';
}

return response('Not allowed', 403);

Example

use App\Models\Task;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;

Gate::define('edit-task', function ($user, Task $task) {
    return $user->id === $task->user_id;
});

Route::get('/l45/task/{task}', function (Task $task) {
    if (Gate::allows('edit-task', $task)) {
        return 'Allowed';
    }

    return response('Not allowed', 403);
});

Key points

  • Gate: a named rule for one action.
  • Use Gate::define to write a gate.
  • Use Gate::allows to ask a gate a question.
  • Use a gate to keep a user to their own records.

In this example, the gate compares the visitor with the task owner. The route asks the gate before it answers. An owner sees Allowed. Another user sees Not allowed. A gate is a rule that says if a user may do one action. Visit /l45/task/1 in the browser as the owner to see the output.

Note

A gate checks one action, so give each action its own gate.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Gate::allows return when the user may not do the action?