skip to Main Content

i have codes about create and update at same time in my Controller file, when i create a new data it should also update a json array column in my User Table

    $rumah = Rumah::create($validatedData);

    $updateData = [
             'lihatAlamat' => json_encode($rumah->id),
             'editAlamat' => json_encode($rumah->id)
             ];
    auth()->user()->update($updateData);
    return redirect('/rumah');

So the problem with this when i create a data, it doesn’t add array data but overwrite whole array inside lihatAlamat and editAlamat column

Example problem like this:

lihatAlamat = ["1","2"]

editAlamat = ["1","2"]

when i create data it becomes:

lihatAlamat = 3

editAlamat = 3

how to add new id number inside array

3

Answers


  1. Chosen as BEST ANSWER

    well, i found my own answer

    $rumah = Rumah::create($validatedData);
    
    //convert json to array
    $lihatAlamat = json_decode(auth()->user()->lihatAlamat);
    
    //work same like above           
    $editAlamat = json_decode(auth()->user()->editAlamat);
    
    //insert id to array
    array_push($lihatAlamat, $rumah->id);
    array_push($editAlamat, $rumah->id);
    
    //query update
    auth()->user()->update([
    'lihatAlamat' => $lihatAlamat,
    'editAlamat' => $editAlamat
    ]);
    return redirect('/rumah');
    

  2. You can use this instead:

    $updateData = [
             'lihatAlamat' => [$rumah->id],
             'editAlamat' => [$rumah->id]
             ];
    

    Hope this solve your problem.

    Login or Signup to reply.
  3. Hi are you trying to update these two (lihatAlamat ,editAlamat) columns values or you want to add old values + new values to combine.

    if i have to to this is would use belongsToMany relationship with pivot table and used sync or async with values so it would be easy to use.
    But as of now you can use this

    In model u can use mutator and accesors

    protected function lihatAlamat(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => json_decode($value),
            set: fn ($value) => json_encode($value),
        );
    }
    
    protected function editAlamat(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => json_decode($value),
            set: fn ($value) => json_encode($value),
        );
    }
    

    Then in controller

    $lihatAlamat = Auth::user()->lihatAlamat;        
    $editAlamat = Auth::user()->editAlamat;
    
    $lihatAlamat[] = $rumah->id
    $editAlamat[] = $rumah->id
    
    auth()->user()->update([
    'lihatAlamat' => $lihatAlamat,
    'editAlamat' => $editAlamat
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search