phprequestlaravel-9

Add a new parameter to request body and fill it with a randomly generated string


This is my controller:

public function RegistrationStore(Request $request)
{
    $validated = $request->validate([
        "first_name" => ['required'],
        'last_name' => ['required'],
        'stable_id' => ['required'],
        'post_id' => ['required', 'in:2,3,4,5'],
        'email' => ['required', 'email', Rule::unique('users', 'email')],
    ]);

    $user = User::create($validated);
    return redirect('/login')->with('message', 'registration successful.');
}

The database table has a password_url column; this column doesn't need to be in the form since it will automatically be generated with a random unique string. is there any way to do this? I've tried inserting:

$random_string = str::random(10);
$request->request->add(['password_url' => $random_string]);

Before $validated but it doesn't add. Am I doing something wrong?


Solution

  • In Laravel, when you use the validate method on a request object, it validates only the fields defined in the validation rules and ignores any other fields.
    So you have to change your validation to:

    $validated = $request->validate([
        "first_name" => ['required'],
        'last_name' => ['required'],
        'stable_id' => ['required'],
        'post_id' => ['required', 'in:2,3,4,5'],
        'email' => ['required', 'email', Rule::unique('users', 'email')],
        'password_url' => ['required'],
    ]);
    

    Or You can merge password_url with $validated

     User::create(array_merge($validated, ['password_url' => $random_string]));