Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

How to create policy with custom parameters?

According to the docs the policy expects either of two options: the User instance and the model instance, or just the User instance, for example:

public function view(User $user, File $file)

or

public function view(User $user)

But in my case, I don't need to pass the model itself, I need to pass a string that identifies the file path in the db and not the File instance:

public function view(User $user, $file_path)

But the following attempt didn't work, I get Too few arguments to function App\Policies\Policy::view() error:

// from the Controller:
$this->authorize('view', File::class, $path);  
// from the Policy:
public function view(User $user, File $file, $path)

How can I pass custom parameters to the policy then?

Thanks!

0 likes
7 replies
jlrdw's avatar

To view an image that someone gave me permission to view:

I would verify that the image is the owners image, next ensure the id of guest viewer is in the related table of allowed to view (just example). For this I wouldn't try to setup all those permissions, I would just setup some if statements as needed.

pseudocode


if user 127 is allowed to view my images then show the image

And setup a redirect or whatever if not allowed. Just a way I'd do it, so suggestion only.

1 like
Ligonsker's avatar

@jlrdw thanks, that's actually really good and I might use it. But even if I use that, shouldn't I place that pseudo code in a Policy to make the code look cleaner?

jlrdw's avatar

@Ligonsker either way, you could write a custom policy that verifies that the guest user is in the owners related table.

But just FYI there are ways of using laravel Authentication with authorization that is much different from the authorization in the documentation.

But my suggestion is you being newer to this stick with the documentation I would only recommend custom authorization to a very experienced programmer.

Myself I would have a custom class to handle this and return true if the guest can view.

1 like
Ligonsker's avatar

@michaloravec @jlrdw thank you guys, Btw, looking into the source code of the authorize method in AuthorizesRequests.php, I realized I had to pass it like so:

$this->authorize('view', [File::class, ["path" => $request->path]]);

and then in the Policy:

public function view(User $user, $args)
{
    dd($args['path'];
}

Please or to participate in this conversation.