SupunSam's avatar

Add Created_by and Modified_by values to database on form submission

Can anyone help me to know how to pass the creating or modifying username to the database automatically whenever submitting a form?

So, in short, it should get the logged-in username and pass it with the rest of the form data. Is this possible?

0 likes
5 replies
mvd's avatar

Hi @supunsam

Why you want to store the name and not the user id? The ID is a much better reference. If users change their name your lost the reference for example.

You don't have to pass the id/name in the form but you can call the user ID in your controller by

Auth()->user()->id; // user ID
Auth()->user()->name; // user name.
1 like
Snapey's avatar

you could use an observer to listen to the creating event and automatically add the id of the logged in user

1 like
uksarkar's avatar
uksarkar
Best Answer
Level 2

Hi @supunsam , if you want to create a reference for created user and modified user you can define a relationship for this. You can follow the code below.

In your controller

public function store(Request $request,Model $model){
    $data = $request->all();
    $data['user_id'] = auth()->user()->id;
    $model->create($data);
    return ........
}


public function update(Request $request,Model $model){
    $data = $request->all();
    $data['modified_user_id'] = auth()->user()->id;
    $model->update($data);
    return ........
}

and then in your model

public function created_user(){
    return $this->belongsTo(User::class);
}

public function updated_user(){
    return $this->belongsTo(User::class, 'modified_user_id');
}

and your database should like this,

  |  ......  |  user_id  |  modified_user_id  |

you modified_user_id column should nullable,

then you can call the relationship like this,

$model = Model::find(1);

$created_user_name = $model->created_user->name

$updated_user_name = $model->updated_user->name
1 like
SupunSam's avatar

Of course. I meant the user-id, not the username. my bad.

SupunSam's avatar

Thank you very much @utpal2015 . Your method simply works. Anyhow, I also figured out to do this with hidden input submissions as well. But your method is a much cleaner one. Thanks.

Please or to participate in this conversation.