Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vajricaaaa's avatar

Insert multiple email addresses in one input and validate this input

Hello, I've got one question. How can I store multiple email addresses that are comma separated in different row in the database and validate this input?

0 likes
16 replies
Sergiu17's avatar

One quick way is

public function store(Request $request)
{
    $request->merge([
        'emails' => explode(',', str_replace(' ', '', $request->emails)),
    ]);
    
    $request->validate([
        'emails.*' => 'required|email'
    ]);

otherwise you could create a custom validator which will do exactly the same thing as in the snippet above

2 likes
vajricaaaa's avatar

@Sergiu17

            $company_recipient = new CompanyReportsRecipient();
            $request->merge([
                $company_recipient->report_id = $company_report->id,
                $company_recipient->email => explode(',', str_replace(' ', '', $request->input('report_recipients'))),
            ]);
            $company_recipient->save();

I did this, but I'm getting explode(): Argument #2 ($string) must be of type string, array given.

Sergiu17's avatar

@vajricaaaa I can't reproduce it, could you show the entire method? is CompanyReportsRecipient a model?

str_replace returns an array only when then third argument is an array

how your form looks like? is it ?

<input name="report_recipients[]"

if so, remove square brackets

vajricaaaa's avatar

@Sergiu17 yeah, and I have an input where can be entered multiple email addresses, with comma or with space, and yes CompanyReportsRecipient is a model and in that table needs to be stored the report_id and the emails, but in different row.

    public function store(Request $request, $id)
    {
        try {
            $company_report = new CompanyReport();
            $company_report->company_id = $id;
            $company_report->type = $request->input('report_type');

            $company_report->save();

            $company_recipient = new CompanyReportsRecipient();
            $request->merge([
                $company_recipient->report_id = $company_report->id,
                $company_recipient->email => explode(',', str_replace(' ', '', $request->input('report_recipients'))),
            ]);
            dd($request->input('report_recipients'));
            $company_recipient->save();
Sergiu17's avatar

@vajricaaaa ok, with comma or white space, we should take another approach

public function store(Request $request, $id)
{
    $request->merge([
        'report_recipients' => preg_split('/[\s,]+/', $request->report_recipients)
    ]);

    $request->validate([
        'report_recipients.*' => 'required|email'
    ]);

	try {
            $company_report = new CompanyReport();
            $company_report->company_id = $id;
            $company_report->type = $request->input('report_type');
            $company_report->save();

			$company_recipient = new CompanyReportsRecipient();
			$company_recipient->report_id = $company_report->id,
			$company_recipient->email = implode(',', $request->report_recipients);
			$company_recipient->save();
1 like
vajricaaaa's avatar

@Sergiu17 I'll try that too. Is this a good approach?

            $input['report_recipients'] = $request->input('report_recipients');

            $data = [];
            foreach (explode(',', $input['report_recipients']) as $report_recipient) {
                $data[] = [
                'report_id' => $company_report->id,
                'email' => str_replace(' ', '',$report_recipient)
                ];
            }
            CompanyReportsRecipient::insert($data);
automica's avatar

@vajricaaaa

trim($report_recipient);

would be neater here:

str_replace(' ', '', $report_recipient)
2 likes
vajricaaaa's avatar

@automica thanks! In my case I don't know how to check if the user entered the emails with space or no space between them, because if I enter it that way the data is stored in one row in the database and should be in separate rows.

automica's avatar

@Sergiu17 correct. But as the OP has already exploded into an array, then I would suspect the str_replace is being used to get rid of rogue spaces before and after the email. There should be no other spaces.

2 likes
vajricaaaa's avatar

@automica That's correct. My only concern is how if the user insert the emails with space between them or without space, how can I check that in my code?

vajricaaaa's avatar

@automica I tried to validate it like this: 'report_recipients' => 'required_if:report_type,Email|email', but when I try to enter two emails in one input with comma separated I'm getting error message from validation that the email must be valid.

automica's avatar

@vajricaaaa I would do the clean up in the request, within 'prepareForValidation' method, creating a new array of emails and then using a rule for each item

eg

 /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'report_recipients' => ['required_if:report_type,Email'],
            'validRecipients' => ['required_if:report_type,Email', 'array'],
            'validRecipients.*' => ['required_if:report_type,Email', 'email'],
        ];
    }

    /**
     * @return void
     */
    public function prepareForValidation()
    {
        $validRecipients = str_replace(' ', '', $this->request->get('report_recipients'));

        $this->merge(['validRecipients' => explode(',', $validRecipients)]);
    }

    /**
     * @return array
     */
    public function messages(): array
    {
        $messages = parent::messages();
        $messages['validRecipients.*.email'] = 'Please ensure your report recipients are valid emails';

        return $messages;
    }

Please or to participate in this conversation.