Passing Multiple Arguments To Laravel Policy Methods

Arie Visser • January 23, 2020

laravel php policies

In most cases, when writing policies in Laravel, you only pass one argument to a policy method, since the authenticated user is already available through dependency injection and no other resources are involved. For example:

$this->authorize('update', $post);

However, you might enter a situation where you want to pass multiple arguments to policy methods.

For example, when you want to check if a user is authorized to update a transaction, it could be required to validate if the source and destination account belong to the same bank.

The update method in the TransactionPolicy might look something like this:

public function update(
    User $user, 
    Transaction $transaction, 
    BankAccount $source, 
    BankAccount $destination
): bool {
    if ($user->ownsTransaction($transaction) === false) {
        return false;
    }

    if ($source->bank_id !== $destination->bank_id) {
        return false;
    }

    return true;
}

In that case, you can pass multiple arguments to the policy method by using an array:

$this->authorize('update', [$transaction, $source, $destination]);

The same syntax can be used when creating a resource, except that the first entry of the array, Transaction::class, is needed to determine which policy to use since the resource does not yet exist:

$this->authorize('create', [Transaction::class, $source, $destination]);