Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make laravel Blueprints morphs method to add column after a specified column

While creating migration scripts I can do something like this

Schema::table('books', function(Blueprint $table)
        {
            $table->string('reference')->after('access');
        });

This will create my reference column after access column. But if I want to use morph how would I do this. I was thinking of doing this

Schema::table('books', function(Blueprint $table)
        {

            $table->morphs('reference')->after('access');
        });

However, this gives me a migration error when I try to run the migration. This is because morphs doesn't have a after method. I am using laravel 5.1. I am not sure how I could have the reference columns after access. Any help or suggestion would be great. Thank you

like image 503
Shadid Avatar asked Sep 29 '17 16:09

Shadid


1 Answers

$table->morphs() is just a shortcut. this is the function behind it (Laravel 5.5):

/**
 * Add the proper columns for a polymorphic table.
 *
 * @param  string  $name
 * @param  string|null  $indexName
 * @return void
 */
public function morphs($name, $indexName = null)
{
    $this->unsignedInteger("{$name}_id");

    $this->string("{$name}_type");

    $this->index(["{$name}_id", "{$name}_type"], $indexName);
}

So this has the same effect:

Schema::table('books', function (Blueprint $table) {
    $table->unsignedInteger("reference_id")->after('access');
    $table->string("reference_type")->after('reference_id');
    $table->index(["reference_id", "reference_type"]);
});
like image 61
stihl Avatar answered Oct 14 '22 15:10

stihl