Support the ongoing development of Laravel.io →
Eloquent Architecture

Dear Laravel enthusiasts,

I'm working on writing a REST API in Laravel and I've run aground on this. This project has several models with attributes that should be shown by the API based on permissions (currently based on Sentry). For example: a Sale has a Customer, Freelancer, selling_price and purchasing_price. When a customer requests all sales he should not be shown what the purchasing price and Freelancer is, while a Freelancer making the same request should not have anything to do with the selling_price.

This requires me to set the $visible property on the Eloquent model dynamically, which I do in the model's constructor using a associative array and function like this:

protected $visibleAccess = [
    'id', //Visible not matter what
    'selling_price' => 'sale_show_client',
    'purchasing_price' => 'sale_show_freelancer'
];

public function __construct(array $attributes = [])
{
    $this->visible = $this->parseAccess($this->visibleAccess);
    parent::__construct($attributes);
}

private function parseAccess(array $access)
{
    $res = [];
    
    $isLoggedIn = Sentry::check();
    $currentUser = $isLoggedIn ? Sentry::getUser() : null;
    foreach ($access as $name => $permission) {
        if (is_int($name)) {
            $res[] = $permission;
        } else {
            if (App::runningInConsole() || ($isLoggedIn && $currentUser->hasAccess($permission))) {
                $res[] = $name;
            }
        }
    }
    
    return $res;
}

I could do this too for appending and filling, and basic eager loading functionality would be possible as well. But eager loading constraints like selecting only certain columns of relation would become difficult but probably not impossible.

But going through all this I'm starting to get the idea that this code smells and that there must be better ways. Knowing I can't be alone on this kind of thing, I'd like to kindly ask your advice.

Please let me know how you'd do this!

Jeroen

Last updated 2 years ago.
0

I´m struggling with the same. Did you find a good solution?

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.