skip to Main Content

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.

3

Answers


  1. 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.

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search