Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I send a custom user to a policy in Laravel 11? #54081

Closed
InforPsico opened this issue Jan 4, 2025 · 2 comments
Closed

Can I send a custom user to a policy in Laravel 11? #54081

InforPsico opened this issue Jan 4, 2025 · 2 comments

Comments

@InforPsico
Copy link

InforPsico commented Jan 4, 2025

Laravel Version

11.36.1

PHP Version

8.3.15

Database Driver & Version

10.4.32-MariaDB Windows 10

Description

I don't know if it's a bug. I have a custom user (tmeUser). I use two types of sessions, the other being the one that comes by default in Laravel (user). When I create a policy, I indicate that tmeUser has to arrive, but I always get the same error.

Steps To Reproduce

When I create a policy, I indicate that tmeUser has to arrive

/**
* @param TmeUser $tmeUser
* @param Phrase $phrase
* @return bool
*/
public function view(TmeUser $tmeUser, Phrase $phrase)
{
return $tmeUser->id === $phrase->tme_user_id;
}

But I always get the error:

App\Policies\PhrasePolicy::view(): Argument #1 ($tmeUser) must be of type App\Models\TmeUser, App\Models\User given, called in .....\laravel\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 816

In Laravel 10 and earlier there has never been any problem, tmeUser always came up. I have created the same project in Laravel 11 and I am encountering this problem.

@cosmastech
Copy link
Contributor

How are you using the policy? In the "can" middleware? Are you calling $tmeUser->can('view', $phrase) directly? Or using Gate::authorize('view', $phrase)?

@InforPsico
Copy link
Author

Using an express call to tmeUser from the controller I have managed to get tmeUser to the policy

if (Gate::forUser(tmeUser)->denies('pass', $phrase)) {
abort(403);
}

So I guess it can be closed because there are ways to solve it.

I would appreciate it if someone could tell me if it would be possible to call the policy using middleware in routes.php as I have done in previous versions of Laravel.

Route::get('phrases/{phrase}/edit','edit')->name('phrases.edit')->middleware('can:pass,phrase');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants