Search code examples
phplaravellaravel-permission

Hide model fields based on user permissions


Lets say user_one has permission to view purchase_price, and user_two does not have this permission.

I want to dynamically hide the purchase_price based on the user permission.

What I have done

I already managed the permissions using spatie package.

What I have tried and searched for

  • I have found that I could use the boot() function the model itself to hide certain fields but I don't know how or it is the best solution also it is a static function.

  • I could make a scope to handle what the API response using if statements and select() but I don't think this is a good solution too.

  • Also I could use Laravel resources.


Solution

  • You can create policies and after that use can() in the controller and @can in blade file for role filters. Click here for more information.

    if ($this->getAuthorisedApp()->cannot('purchase_price'))
        {
            $this->setHidden(['purchase_price']);
    
            //  Or, $this->setVisible(['example_key']), if this works better for you.
        }