Reputation: 14791
I am developing a Web application using Laravel Nova. Nova is quite a new CMS system for Laravel. What I am now having trouble with many to many relationship and presenting data.
I have a users table with the following data
users - id, name, email, role
Then I have a departments table with the following data.
departments - id, name, code
They have many-to-many relationship with a pivot table like this.
departments_users - id, department_id, users_id
In the User resource if I added this in the fields method
public function fields(Request $request)
{
return [
ID::make()->sortable(),
//other fields
BelongsToMany::make("Departments")
];
}
Because of I added BelongsToMany in the User resource, if I go to the user details page, I will see something like this.
Basically what I mean is the option to display list of departments of users and option to attach departments to user. But I do not want to display that option/list all the time. I only want to display it based on the role. I mean something like this in the fields method. Please, read the comment in the following code.
public function fields(Request $request)
{
return [
ID::make()->sortable(),
//other fields
BelongsToMany::make("departments")//Do this only if the user role is "staff"
];
}
Upvotes: 0
Views: 3317
Reputation: 814
This is simple to achieve using laravel nova authorization.
You can add ->canSee()
to BelongsToMany
field.
You didn't specified which user has to have role "stuff". Logged in or edited.
If logged then just make:
BelongsToMany::make("departments")
->canSee(function ($request) {
return $request->user()->role == 'stuff';
}),
If edited user:
BelongsToMany::make("departments")
->canSee(function ($request) {
return $this->role == 'stuff';
}),
For more info check Field Authorization docs
Upvotes: 3