Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new column on the basis of values in the existing column in laravel

Tags:

php

mysql

laravel

I have these columns in the table:

  • id
  • name
  • status
  • type

Status should be 0 or 1.

  • 0 for inactive
  • 1 for inactive.

I want to add status_name field in my item listing. Is this possible?

$items = Item::where('type', 'test');
if(item.active == 1)
{
   // add new column status_name="active"
}
else
{
   // add new column status_name="inactive"
}

$items->get();

I don't want to use loop. Is there any way to do this with this query only without using loop.

like image 771
Pritika Avatar asked Dec 20 '25 15:12

Pritika


1 Answers

In this example, I wanted to turn a VARCHAR field called curbsidePickup that either contains "true" or "false" (strings) into a TINYINT field called pickup to make it atomary. For this, you have to iterate all items before getting rid of the old field:

<?php

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

class ChangeOrdersForBooleanPickup extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->boolean('pickup');
        });
        DB::table('orders')
            ->where('curbsidePickup', '=', 'true')
            ->update([
                'pickup' => true
            ]);
        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn('curbsidePickup');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->string('curbsidePickup');
        });
        DB::table('orders')
            ->where('pickup', '=', true)
            ->update([
                'curbsidePickup' => 'true'
            ]);
        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn('pickup');
        });
    }
}
like image 116
Martin Braun Avatar answered Dec 22 '25 03:12

Martin Braun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!