PASSWORD RESET

Your destination for complete Tech news

How to set default values in Laravel migration file?

602 0
< 1 min read

To set default values in a Laravel migration, you can use the default method on the column definition.

For example, suppose you have a users table and you want to add a status column with a default value of active. You can use the following migration:

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

class AddStatusToUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('status')->default('active');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('status');
        });
    }
}

This will add a status column to the users table with a default value of active.

You can also use the default method to set default values for other data types, such as integers or timestamps. For example:

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

You can then run the migration using the php artisan migrate command.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.