Feralheart
Feralheart

Reputation: 1928

Laravel: Database - More "log column"

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

The last three should be contain user.id.

What is the better method?

Upvotes: 2

Views: 162

Answers (1)

Sazzadur Rahman
Sazzadur Rahman

Reputation: 2930

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');
    }
}

Upvotes: 2

Related Questions