Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add decimal column to existing table in Laravel 5.3 migration

I have tried following 3 codes in a Laravel 5.3 project to add new decimal column to an existing table. But it's giving same error every time.

Schema::table('mileages', function (Blueprint $table) {
    $table->addColumn('decimal', 'cost');
});

and

Schema::table('mileages', function (Blueprint $table) {
    $table->addColumn('decimal', 'cost', ['default'=>0]);
});

and

Schema::table('mileages', function (Blueprint $table) {
    $table->addColumn('decimal', 'cost', ['default'=>'0,0']);
});

The error was :

[Illuminate\Database\QueryException]                                                                                 
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that  
corresponds to your MariaDB server version for the right syntax to use near ' ) not null' at line 1 (SQL: alter table `mileages` add `cost` decimal (, ) not null) 

am i missing something ?

like image 500
Eranda Avatar asked Feb 14 '17 09:02

Eranda


2 Answers

You're trying to use ->addColumn() which isn't quite the right syntax.

Create a new migration, php artisan make:migrate add_cost_column_to_mileages.

Then inside your migration, you want it to look like this for up:

Schema::table('mileages', function (Blueprint $table) {
    $table->decimal('cost', 5,2); //Substitute 5,2 for your desired precision
});

And this for down:

Schema::table('mileages', function (Blueprint $table) {
    $table->dropColumn('cost');
});

This is from the docs here, although they don't make it explicitly clear.

like image 117
James Avatar answered Oct 20 '22 15:10

James


Schema::table('mileages', function (Blueprint $table) {
    $table->addColumn('decimal',2);
});
like image 1
shazim ali Avatar answered Oct 20 '22 16:10

shazim ali