Agus Suparman
Agus Suparman

Reputation: 89

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::update() must be of the type array, object given

I want to update a data in the database i have controller

public function update(Identity $identity, Request $request)
{
  $data = new Identity();
  $data->date  = $request['date'];
  $data->code   = $request['code'];
  $data->name   = $request['name'];
  $request->user()->identity()->update($data);
  Session::flash('flash_message', 'Update success.');
  return redirect('identity.index');
}

Model Identity

public function user()
{
// Each data is owned by only one user
return $this->belongsTo('App\User');
}

Model User

public function identity()
{
// Each user will have a lot of data
return $this->hasMany('App\Identity');
}

And i found an error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::update() must be of the type array, object given.

Upvotes: 0

Views: 12027

Answers (2)

Sandeesh
Sandeesh

Reputation: 11916

You already have the Identity model with the route model binding. You can do one of the below.

public function update(Identity $identity, Request $request)
{
    $identity->date = $request['date'];
    $identity->code = $request['code'];
    $identity->name = $request['name'];
    $identity->save();

    Session::flash('flash_message', 'Update success.');
    return redirect('identity.index');
}

Or (Make sure you set the $fillable property in the model for this to work)

public function update(Identity $identity, Request $request)
{
    $identity->update([
        'date' => $request['date'],
        'code' => $request['code'],
        'name' => $request['name'],
    ]);

    Session::flash('flash_message', 'Update success.');
    return redirect('identity.index');
}

Upvotes: 1

Matt S
Matt S

Reputation: 15374

This line

$data = new Identity();

creates an object. Below that you are setting its properties. Instead, it looks like you can pass your properties directly into the function:

public function update(Identity $identity, Request $request)
{
  $request->user()->identity()->update(array($request));
  ...
}

Of course you might also want to restrict your request to just what's needed:

public function update(Identity $identity, Request $request)
{
  $params = array_intersect_key(array($request), array_flip(['date', 'code', 'name']))
  $request->user()->identity()->update($params);
  ...
}

Upvotes: 0

Related Questions