I want to override the timestamps()
function found in the Blueprint
class. How can I do that?
e.g.,
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('password');
$table->string('email');
$table->string('name');
$table->timestamps(); // <-- I want this to call my method instead of the one found in the base Blueprint class
});
}
Just to add a few points to Marcel Gwerder's answer (which is already great):
You can shorten
DB::connection()->getSchemaBuilder()
toDB::getSchemaBuilder()
because Laravel automagically forward the method call to the connection instance.Each call to the
Schema
Facade already creates a newSchema\Builder
instance, as can be seen in thegetFacadeAccessor()
method in the following files:(edit 2016-03-06)
A GitHub issue has been recently opened about this: #12539.
There is a new
blueprintResolver
function which takes a callback function which then returns theBlueprint
instance.So create your custom Blueprint class like this:
And then call the
blueprintResolver
function where you return yourCustomBlueprint
instance.I'm not sure if creating a new schema instance with
DB::connection()->getSchemaBuilder();
is state of the art but it works.You could additionally override the
Schema
facade and add the custom blueprint by default.Marcel Gwerder's answer was a life saver. Like some of the users commented there, I wondered if this could be done more automagically. My goal was similarly to overwrite the
timestamps
method. After some tinkering, this is what I ended up with which is working for me:I created a file at
app/Classes/Database/Blueprint.php
:I created a file at
app/Facades/Schema.php
Inside
config/app.php
I updated the alias for Schema as follows:Now, in my migrations, like the below, when I call
timestamps()
, it calls my overwritten method.