简体   繁体   中英

Update column automatically based on value of another column (same table) in Laravel (7)

I am a newbe of Laravel. This is my (pivot) table:

id | user_id | sponsorship_id | created_at | updated_at | end_date

I would like to populate the end_date column automatically based on the value of the created_at column with these conditions:

if sponsorship_id == 1 add 24 hours to the created_at and put the new date in the end_date column

if sponsorship_id == 2 add 72 hours to the created_at and put the new date in the end_date column

if sponsorship_id == 3 add 144 hours to the created_at and put the new date in the end_date column

This is currently in my controller:

public function updateSponsorship(Request $req, User $user){

    $dataSponsor = $req->all();

    $new_user = new User();
    $new_user->fill($dataSponsor);
    $user->update($dataSponsor);

    if(array_key_exists('sponsorships', $dataSponsor)){
        $user->sponsorships()->attach($dataSponsor['sponsorships']);
    } else {
        $user->sponsorships()->detach();
    }
    return redirect()->route('admin.users.show', $user);

 }`

Data is sent through a FORM from edit.blade.php

Any suggestion??

Thanks!

It makes use of eloquent events to set the 'end_date' attribute of your model

you can check the below link for more info

https://stackoverflow.com/a/27936307/3739625

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