Press ESC to close

Manoj Bist

How To Add a Default Value To Column in Laravel Migration

Add default value to columns in laravel migration

 

Here I will be sharing, how we can add default value to column in laravel migration. As well as I will be adding an example to create migration in laravel. I will be creating a table of posts, table posts with columns title, content, and timestamps.

For this post, I am assuming that you already have installed Laravel and configured your database.

In the first step, we will be creating a migration

Create Migration


    	php artisan make:migration create_posts_table
    

Done! just created migration. and next, we will be adding columns to the migration file and creating an actual table in our database.

Adding columns and Add Default value to column migration

Go to the database/migrations directory, and open the recently created migration file, with your favorite code editor, and add the following code


    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            //here is the default value
            $table->string('title', 55)->default('Untitled aritcle');
            $table->text('content');
            $table->timestamps();
        });
    }
    

In above code, you can see, i have added default() function chained with $table->string() function. That function is responsible for adding default value to the column. Here I added the default value “Untitled article”. This value will be added if I don’t send a value for the title column from the posting form.

Hope this helped you!

Manoj Bist

A Passionate Web Developer/Designer With over 6 years of experience in the industry, Manoj Bist is a seasoned professional who combines technical expertise with a down-to-earth demeanor. As a lover of both technology and design, he thrives on creating seamless digital experiences that captivate and inspire.

Leave a Reply

Your email address will not be published. Required fields are marked *