Home > Blockchain >  Laravel Update one form data to different tables using relation?
Laravel Update one form data to different tables using relation?

Time:01-19

I have a model user contains below

class User extends Authenticatable implements MustVerifyEmail
{
 public function friends()
    {
        return $this->hasMany(Friends::class);
    }
}

and a friends models contains following

class friends extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Controller contain following

public function update(ProfileUpdateRequest $request)
    {
        $request->user()->fill($request->validated());
        $request->user()->save();

        return Redirect::route('profile.edit')->with('status', 'profile-updated');
    }

rules contains related table field interest, i wanted to update that field,

public function rules()
    {
        return [
            'name' => ['string', 'max:255'],
            'email' => ['email', 'max:255', Rule::unique(User::class)->ignore($this->user()->id)],
            'interest' => ['required', 'min:3', 'max:10000']
        ];
    }

when i update the form it only update the user model data and not the friends model field interest, can someone help please?

CodePudding user response:

Going by what you've posted thus far, I would say that fill() will take care of the values native to User model. However, if you want to fill in the values of a one-to-many relation, you have to take an extra step.

One-to-many relationship: https://laravel.com/docs/9.x/eloquent-relationships#one-to-many

Inserting data into relations: https://laravel.com/docs/9.x/eloquent-relationships#inserting-and-updating-related-models

In the controller, you can try something like:

// import App\Models\friends as Friend;


$request->user()->friends()->save(new Friend([
  'interest' => $request->interest
]));

The above code adds new friends. To update existing friends, you can do this:


$friends = $request->user()->friends;

foreach ($friends as $friend) {
  $friend->interest = $request->interest;
  $friend->save();
}

If the code doesn't work, check if "interest" is added to the $fillables property in your "friends" model. It should go through, but if you use a method like "friends::updateOrCreate", it will not populate if it's not in the $fillables array property.

See mass-assignment: https://laravel.com/docs/9.x/eloquent#mass-assignment

  • Related