Protected/Private properties missing

Ok, now I see what you are talking about. Thanks!
I did not know that there is something “locked” already and this is again not documented.
But this way it appears that the lockPropertyFromSync() could be a right thing to use. The only problem is that it is not documented and might be changed in the future releases.

Looks like this method no longer exists.

Recommended solution:

public function updatingFoo()
{
    // Do not let user change $foo, abort with unauthorized error
    return abort(403);
}

You are right. My current work almost the same, just a small addition - it is useful to make this protected property as array, so that you can pack everything there.

Here is my current trait to attach models:

<?php
namespace App\Traits;

use Exception;
use Illuminate\Database\Eloquent\Model;

trait PersistentProperties
{
    protected $securePersistentProperties = true;
    public $persistentProperties = [];

    // add properties in a format ['propertyName' => Model]
    protected function addPersistentProperties(array $modelProperties)
    {
        foreach($modelProperties as $property => $model){
            if($model instanceof Model){
                $this->persistentProperties[$property] = [
                    'id' => $model->getKey(),
                    'class' => get_class($model)
                ];
                $this->computedPropertyCache[$property] = $model;
            }
        }
    }

    // just in case you need to remove
    protected function removePersistentProperty($property)
    {
        if(!is_array($property)) $property = [$property];
        foreach ($property as $prop) {
            unset($this->persistentProperties[$prop]);
            unset($this->computedPropertyCache[$prop]);
        }
    }

    public function initializePersistentProperties()
    {
        if($this->securePersistentProperties){
            // $this->lockPropertyFromSync('persistentProperties');
        }
    }

    public function __get($property)
    {
        // check if this is a persistent property
        $persistentProperty = $this->persistentProperties[$property] ?? null;
        if($persistentProperty) {
            $model = $this->computedPropertyCache[$property] ?? null;
            if(!$model) {
                $model = $persistentProperty['class']::find($persistentProperty['id']);
                $this->computedPropertyCache[$property] = $model;
            }
            return $model;
        }
        return parent::__get($property);
    }

    public function updatingPersistentProperties($name)
    {
        if($name == 'persistentProperties') throw new Exception('Unable to modify "persistentProperties"!');
    }
}

And in the class you do something like this:

use PersistentProperties;

    public function mount(Stage $stage)
    {
        $this->addPersistentProperties(['stage' => $stage]);
    }
    public function render()
    {
        $stage = $this->stage;
       ...
1 Like