GitHub

Authorization

TinyMVC provides a simple yet powerful authorization system through the Gate class, allowing you to define abilities and check user permissions throughout your application.

Defining Abilities

Abilities are defined using closures that determine if a user can perform an action:

// In your service provider or bootstrap file
gate()->define('edit-post', function (?User $user, Post $post) {
    // Guests can't edit posts
    if (!$user) {
        return false;
    }
    
    // Admins can edit any post
    if ($user->is_admin) {
        return true;
    }
    
    // Users can only edit their own posts
    return $user->id === $post->user_id;
});

Checking Abilities

Use the helper functions to check permissions:

// Check if user can edit a post
if (can('edit-post', $post)) {
    // Show edit button
}

// Alternative check
if (cannot('edit-post', $post)) {
    abort(403);
}

// Force authorization check (throws exception if denied)
authorize('edit-post', $post);

Before Callbacks

Register callbacks that run before all ability checks:

// Give admin full access
gate()->before(function (?User $user, string $ability) {
    if ($user && $user->is_admin) {
        return true;
    }
    
    return null; // Continue with normal checks
});

Controller Authorization

Authorize actions in controllers:

public function update(Post $post)
{
    authorize('edit-post', $post);
    
    // Update the post...
}
Best Practice: Keep your ability definitions organized by registering them in a service provider or dedicated authorization file.

Full Example

// Define abilities
gate()->define('manage-users', function (User $user) {
    return $user->is_admin;
});

gate()->define('edit-settings', function (User $user, Account $account) {
    return $user->id === $account->owner_id;
});

// In controller
public function edit(Account $account)
{
    authorize('edit-settings', $account);
    
    return view('account.edit', compact('account'));
}

// In view
<?php if(can('manage-users')): ?>
    <a href="/admin/users">Manage Users</a>
<?php endif ?>