2

I want to add some other columns next to the created_at and updated_at columns, for example:

  • deleted_at
  • creator
  • updater
  • deleter

The last three should be contain user.id.

What is the better method?

  • A. place it in the migration
  • B. Edit the Blueprint class?
2
  • Do you want it for all of your migrations? Commented Aug 12, 2017 at 16:35
  • @SazzadurRahman yes, and for all of my projects Commented Aug 12, 2017 at 17:04

1 Answer 1

2

Instead of directly editing Laravel's core Blueprint class you should extend it and add functionality according to your specific needs. Here is an example how you can do this.

Create a CustomBlueprint class in database directory that extends core Blueprint class, which contains definitions of your custom columns.

<?php

namespace Database;

class CustomBlueprint extends \Illuminate\Database\Schema\Blueprint
{

    public function customColumns() {
        $this->integer('creator')->nullable();
        $this->integer('updater')->nullable();
        $this->integer('deleter')->nullable();
    }
}

After creating the custom blueprint run

composer dumpautoload

Then create your migrations, such as

php artisan make:migration create_tests_table

In your migration file use customColumns method like this

<?php

use Database\CustomBlueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;

class CreateTestsTable extends Migration
{
    public function up()
    {
        $schema = DB::connection()->getSchemaBuilder();

        $schema->blueprintResolver(function($table, $callback) {
            return new CustomBlueprint($table, $callback);
        });

        $schema->create('tests', function($table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
            $table->customColumns();
        });
    }

    public function down()
    {
        Schema::dropIfExists('tests');
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried it, but I got [Symfony\Component\Debug\Exception\FatalThrowableError] Class 'Database\CustomBlueprint' not found on migration
Run composer dumpautoload then it should be fixed, I am also updating the answer with this fix

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.