Ad
Laravel: How Can I Write A Policy Class For API Methods On A Nested Resource Controller?
I have a many to many relationship that I'm working with between User
and Task
models. A user belongs to many tasks and a task belongs to many users. I have a pivot table called task_user
.
In my API, I have a route defined as follows:
Route::get('/users/{user}/tasks', '[email protected]');
I want to write a policy to enforce that the currently logged in user, auth()->user
, is the user being requested in the route. Basically, a user can only view their own tasks.
How can I write a policy class for the nested resource controller TaskUserController
?
Ad
Answer
Nesting of your resource has nothing to do with making policies.
Make your UserPolicy.
class UserPolicy()
{
public function view(User $authorizedUser, User $user) {
return $authorizedUser->is($user);
}
}
In your controller, you can authorize the action, with the authorize()
helper. Alternatively it can be executed in your form request with Auth::user()->can()
.
class TaskController {
public function all(User $user)) {
$this->authorize('view', $user);
return $user->tasks;
}
}
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad