Home > Enterprise >  Ignore variable in update Laravel
Ignore variable in update Laravel

Time:10-16

how i can make variable in Update Statement who is ignored. I tried like this but it doesn't work.

$dl = '';
$select = DB::table('Character')->where('Name', '=', $request->char)->first();

    if($select->Class == 64 OR $select->Class == 65 OR $select->Class == 66)
    {
        $newcom = $select->Leadership   $request->com;
        $dl .= 'Leadership '.'=> ' .$newcom;
    }

// Update
DB::table('Character')
      ->where('Name', '=', $request->char)
      ->update([
           'Strength' => $select->Strength   $request->str,
            $dl
      ]);
   

I get Invalid column name '0'. in error list.

CodePudding user response:

This should fix your issue:

$select = DB::table('Character')->where('Name', '=', $request->char)->first();

if($select->Class == 64 OR $select->Class == 65 OR $select->Class == 66)
{
    $select->Leadership = $select->Leadership   $request->com;
}
$select->Strength = $select->Strength   $request->str;
$select->update();

since you already have the $select object, you just have to update Leadership properties conditionally and push the update.

CodePudding user response:

Create an array with the data to update before the actual update. Then you can conditionally push the columns you need to update:

// The data to update, only add what should always be updated as default
$dataToUpdate = [
    'Strength' => $select->Strength   $request->str,
];

// Check if we should update 'Leadership' as well
if($select->Class == 64 OR $select->Class == 65 OR $select->Class == 66)
{
    // We should, add that to the array with data to update
    $dataToUpdate['Leadership'] = $select->Leadership   $request->com;
}

// Update using the array we just created with the data
DB::table('Character')
    ->where('Name', '=', $request->char)
    ->update($dataToUpdate);

CodePudding user response:

Trying to use

$dl .= 'Leadership '.'=> ' .$newcom;

to create an array element won't work. It just creates a string which it's trying to assign to column 0 (the default array index assigned to it).

Instead, you should build a proper associative array of data and use that for the update, so assign the main values when you create the array. Then add any optional values as you go along (such as Leadership). Something like...

$data = ['Strength' => $select->Strength   $request->str,];

if($select->Class == 64 OR $select->Class == 65 OR $select->Class == 66)
    {
        $newcom = $select->Leadership   $request->com;
        $data['Leadership'] = $newcom;
    }

// Update
DB::table('Character')
    ->where('Name', '=', $request->char)
    ->update($data);

Passing the final array to your update statement.

  • Related