Datetime field in Laravel migration

Created at 22-Aug-2022 , By samar

Datetime field in Laravel migration

We’ll attempt to use programming in this lesson to solve the "Datetime field in Laravel migration" puzzle.

Create datetime field in Laravel using migration.

You have to create a migration file after that you have to add a column using $table->dateTime('posted_at')->nullable(); code snippet. After changes in migration file you have to run php artisan migrate command to create a datetime column type in database table.

  • Create datetime field in Laravel using migration

    Create migration file using below command.

    php artisan make:migration add_posted_at_column_to_posts_table --table=posts
    

    Open created migration file under database/migrations folder and paste below code in up method.

    $table->dateTime('posted_at')->nullable();
    

    After implementation your code will look like below.

    <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    return new class extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::table('posts', function (Blueprint $table) {
                $table->dateTime('posted_at')->nullable();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::table('posts', function (Blueprint $table) {
                //
            });
        }
    };
    

    Run the below command to migrate.

    php artisan migrate
    

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.