After PUT request object properties are shown as strings

Viewed 36

Started working with Laravel 8 and little bit struggling with PUT request. Whenever I try to update(create actually new fields on update) a user with new properties they are shown as strings.

Here's my User migratiomn

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('username');
        $table->string('password');
        $table->string('type')->nullable();
        $table->string('profile')->nullable();
        $table->timestamps();
    });
}

Here's my function from controller

  public function update(Request $request, $id)
    {
        $user = User::find($id);

        $user->update([
            'profile' => [
                'company_name' => $request->input('company_name'),
                'company_vat' => $request->input('company_vat'),
            ],
        ]);

        return response($user, 201);
    }

And here's how it looks from get request after doing put request. request

So the whole issue that they shouldn't be displayed as strings and actually I can't find a solution.

1 Answers

You need to add attribute casting to your model, it will save it as a json string in the database and json decode it on calls.

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'profile' => 'array',
    ];
}
Related