samedi 9 janvier 2016

Laravel 5.1 how to update related model

I have the following models with fillable properties defined:

class User {

   protected $fillable = [
    'first_name',
    'last_name',
    'email',
    'password',
  ];

   public function profile()
   {
      return $this->hasOne('App\Profile');
   }  

    public function roles()
   {
      return $this->belongsToMany('App\Role')->withTimestamps();
   } 

}


Class Profile {

    protected $fillable = [
      'user_id',
      'start_dt',
      'end_dt',
      'gravatar',
   ];

   protected $dates = ['start_dt', 'end_dt'];

   public function user()
   {
      return $this->belongsTo('App\User');
   }

}

I have a form to update the user which includes a check box array:

 <div class="form-group ">
  <label for="start_at">Start Date</label>
  <input id="start_dt" class="form-control" type="text" name="start_dt">
 </div>

 <div class="checkbox">
    <label>
     <input id="Admin" type="checkbox" value="2" name="user_roles[]" checked="checked"> Admin
    </label>
 </div>

In my controller I have the following method to update the user profile but I get error: ErrorException in helpers.php line 671: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

It seems like using $user->profile()->update($request->all()); is causing this error because the request object contains an array for the user_roles. But why should this matter as I've defined the mass fillable attributes on the Profile class?

public function update(UserRequest $request, $id)
{
    $user = User::findOrFail($id);

    $user->update($request->all());

    $user->roles()->sync($request->input('user_roles'));

    $user->profile()->update($request->all());

    flash()->success('User details have been updated');

    return redirect('/user/' . $id . '/edit');
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire