'Adding a new key-value in Update Method in Laravel

I'm working on an app where users will define the name and value of a field. I achieved it in create method. Now I want to edit the game added. But user can change the name of the field in the keys array.

Let me know if there's any solution in laravel for this.

Trying to access array offset on value of type null

View Code :

<form action="{{ route('games.update', $games->id) }}" method="POST" id="edit-form">

@csrf
@method('put')

     @for ($i = 0; $i < count($keys); $i++) <div class="row">
         <div class="col-4">
             <div class="form-group my-2">
                 <input type="text" name="keys[]" value="{{ $keys[$i] }}" class="form-control">
             </div>
         </div>
         <div class="col-4">
             <div class="form-group my-2">
                 <input type="text" name="values[]" value="{{ $values[$i] }}" class="form-control">
             </div>
         </div>
         </div>
         @endfor
</form>

Controller Code

public function update(Request $request, $game)
{

        // Getting the Game 
        $games =  Games::find($game);
        $account = Accounts::where('accountName', '=' , $request->accountName)
                            ->orWhere('_id','=',$request->accountName)->first();
    
        // Loop to get keys and values. 
    
        for ($i=0; $i < count($keys); $i++) {
            $games[$request->key[$i]] = $request->value[$i];
        }
    
    }

Model Code

class Games extends Model
{

    protected $guarded = [];
    use HasFactory;

}

I have tried checking if the key already exist or not and then wanted to figure out a solution later. But laravel throws an error even when i'm checking if it exists or not

Condition:

$keys = array_filter($request-\>keys);
$values = array_filter($request-\>values);

for ($i=0; $i \< count($keys); $i++) {
         if(array_key_exists($keys\[$i\], $games)){
                echo "wokring".$i."<br>";
         } else {
                dd("");
         }
}

Error:

array_key_exists(): Argument #2 ($array) must be of type array, App\Models\Games given

This is because I'm giving the model as an array. I could not think of a solution other than this.

Using Laravel 8 with MongoDB



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source