0
votes

I am implementing a method to automatically escape (htmlentities) user obtained data before returning. At the moment I have a BaseModel that all the other models inherit from, implemented as follows:

<?php

class BaseModel extends Eloquent
{
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        // Escape required fields when necessary
        if (isset($this->escapable) && in_array($key, $this->escapable)) {
            $value = e($value);
        }

        return $value;
    }

    public function attributesToArray()
    {
        $array = parent::attributesToArray();

        if (isset($this->escapable)) {
            array_walk($array, function (&$value, $key) {
                if (in_array($key, $this->escapable)) {
                    $value = e($value);
                }
            });
        }

        return $array;
    }

}

In the model itself I simply extend BassModel instead of Eloquent and set an $escapable array in much the same way as the $fillable attribute

protected $escapable = [
    'first_name',
    'last_name',
    /* etc */
];

This works 100% when fetching an individual attribute - getAttribute($key) - and when returning an entire collection - attributesToArray(), my question is are there other situations I haven't accounted for that could allow unescaped data to be returned? I see there's a getAttributes() function in Model.php, in what situations would this be called?

1

1 Answers

0
votes

I think you are pretty save with that implementation.

getAttributes() is only used internally once, and that's when dealing with pivot models. No need to worry about that.