简体   繁体   中英

how to update value in one column and automaticaly updated another column at different table laravel

i try to update value of name in table student and auto updated in column name at table users

my controller code is

public function update(Request $request, $id)
    { 
        $user = User::where('id', $id)->first();
        $user->name = $request->name;
        $user->save();

        $student= Student::where('id', $id)->first();
        $student->name = $request->name;
        $student->save();

       return redirect()->route('profilestudent.edit', Auth::user()->student->id);
   }

no errors but it change another user's name at table users.

You can try with mutators :

class User extends Model
{
    public function setNameAttribute($value)
    {
        $student= Student::where('user_id', $this->id)->first() if id is not key in Student
        $student->name = $value;
        $student->save();
        $this->attributes['first_name'] = $value;
    }
}

You should use the observers. When a User is updated, the Student will automatically also being updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM