4
votes

Okay so i'm trying to make some simple database schemas using Laravel 5.2 migrations. They're pretty basic for now. The issue is that the result table created does not reflect in mysql what I dictated in the schema builder. For example:enter image description here creates the following table (ignore the picture after the table): enter image description here

I'm pretty sure that If I wanted to allow nulls I should be using nullableTimestampts() also no default values and no "on update CURRENT TIMESTAMP" etc.

What am I missing here? The aritsan commands were pretty straightforward:

php artisan make:migration create_table_institutes --create=institutes
php artisan migrate

I am on Ubuntu 14.04, php7, Apache mysql Here is my seeding code:

DB::table('institutes')->insert([
    'name' => 'Ncbi',
    'base_curl' => 'eutils.ncbi.nlm.nih.gov/entrez/eutils/',
]);
1
You can use ->useCurrent() for setting default values.Bharat Geleda
Thanks, I didn't know that, I can also update it manually via sql. Is this though how it's supposed to be done? I'm ultimately trying to find why isn't the table created properlyKonstantinos Daskalopoulos
Tbh, I don't think that should be the correct schema. What version of Laravel are you using?Bharat Geleda

1 Answers

3
votes

Actually the Schema Builder's timestamps method creates nullable timestamp columns by design since Laravel 5.2. The nullableTimestamps method is just a synonym which is more explicit as to how the timestamps are created, and all it does is call the timestamps method internally.

So if you need timestamp fields that are not nullable, then you need to manually create them. Also for the created_at column to be populated automatically with the current timestamp by MySQL, it needs a default values. So this:

$table->timestamps();

Should be replaced with this:

$table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->dateTime('updated_at')->nullable();

For versions older that MySQL 5.6.5 where DATETIME columns cannot have a default value, a TIMESTAMP column can be used instead:

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

Although, if you're using Eloquent, aside from the created_at column which is always populated when a model entry is created, the other columns should be nullable as they will get values assigned only when updated or soft deleted.