Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are the methods in laravel ColumnDefinition class implemented?

To write migrations in laravel, we have different methods to apply them to our $table columns. One of them, for example, is nullable() which makes that column nullable.

I want to know, where do functions like nullable() have been defined. I cannot see anything such as public function nullable() in laravel. This must be in one of these classes but I can not find it:

1) vendor\laravel\framework\src\Illuminate\Database\Schema\ColumnDefinition

2) vendor\laravel\framework\src\Illuminate\Support\Fluent

3) vendor\laravel\framework\src\Illuminate\Database\Schema\Blueprint

or any other class extended from these or any other trait used in one of these.

Where do these functions have been defined?

like image 769
Majid Alaeinia Avatar asked Oct 21 '25 12:10

Majid Alaeinia


2 Answers

The method nullable itself does not exist. If you take a look at the Blueprint class, the addColumn method returns an instance of ColumnDefinition.

And ColumnDefinition is an empty class which simply extends the Fluent class that contains the following __call method:

/**
 * Handle dynamic calls to the fluent instance to set attributes.
 *
 * @param  string  $method
 * @param  array   $parameters
 * @return $this
 */
public function __call($method, $parameters)
{
    $this->attributes[$method] = count($parameters) > 0 ? $parameters[0] : true;

    return $this;
}

Therefore, when you execute $table->string('name')->nullable();, it goes into the __call because the nullable method does not exist and simply saves the nullable attribute to true. Which also translates to:

$this->attributes['nullable'] = true;

And then in the MySqlGrammar class, it checks if the column is nullable or not:

/**
 * Get the SQL for a nullable column modifier.
 *
 * @param  \Illuminate\Database\Schema\Blueprint  $blueprint
 * @param  \Illuminate\Support\Fluent  $column
 * @return string|null
 */
protected function modifyNullable(Blueprint $blueprint, Fluent $column)
{
    if (is_null($column->virtualAs) && is_null($column->storedAs)) {
        return $column->nullable ? ' null' : ' not null';
    }
}

For more information about __call: https://www.php.net/manual/en/language.oop5.overloading.php#object.call

like image 196
Chin Leung Avatar answered Oct 24 '25 00:10

Chin Leung


Modifier functions like nullable differs depending on database driver (or Grammar as declared in laravel)

you can find what you want in vendor\laravel\framework\src\Illuminate\Database\Schema\Grammars\

for mysql, check Illuminate\Database\Schema\Grammars\MySqlGrammar

like image 33
N69S Avatar answered Oct 24 '25 01:10

N69S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!