mysqllaravellaravel-8

Is there anyway to assign a default value of a table equal to the id itself?


So I want to set the default value of the column order equal to the id. This is pretty much for sorting purposes.

Is there anyway to do it? Or would there be a better way to achieve the same purpose?

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->bigInteger('order');
    $table->string('path');
    $table->text('description')->default('');

    $table->timestamps();
});

Solution

  • You can do it in the following way. The created event will be called once it is created and will never call on updating

    class Post extends Model
    {
        protected static function booted() {
            self::created(function (self $post){
                $post->order = $post->id;
                $post->save();
            });
        }
    }
    

    Laravel Documentation