archtechx / virtualcolumn

Eloquent Virtual Column package.
MIT License
72 stars 12 forks source link

Allow to use guardable functions #15

Closed b09v closed 1 year ago

b09v commented 1 year ago

This pull request allows you to continue using the guarded function of eloquent. Now to use virtualcolumn I always have to set $guarded = []; With this change, however, you can continue to use the protection function as you always have. We can find the default function in vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php

    /**
     * Determine if the given column is a valid, guardable column.
     *
     * @param  string  $key
     * @return bool
     */
    protected function isGuardableColumn($key)
    {
        if (! isset(static::$guardableColumns[get_class($this)])) {
            $columns = $this->getConnection()
                        ->getSchemaBuilder()
                        ->getColumnListing($this->getTable());

            if (empty($columns)) {
                return true;
            }
            static::$guardableColumns[get_class($this)] = $columns;
        }

        return in_array($key, static::$guardableColumns[get_class($this)]);
    }

i changed it a bit to allow all columns to be guarded

    /**
     * Determine if the given column is a valid, guardable column.
     *
     * @param  string  $key
     * @return bool
     */
    protected function isGuardableColumn($key)
    {
        return true;
    }
stancl commented 1 year ago

Could you clarify a bit what this change fixes?

b09v commented 1 year ago

Could you clarify a bit what this change fixes?

Now to use mass assignment I have to define protected $guarded = [];. If I want to use mass assignment and add some variale guardable like this protected $guarded = ['id', 'name'], i can't do this because of the default function in eloquent protected function isGuardableColumn($key), that will check if the virtual column added exists as schema column in the database table. By overriding this function to not check if the column exists in the schema, I can use mass assignment with guarded variable and new virtual columns.

stancl commented 1 year ago

Don't think this change makes much sense here.