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?
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
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