Skip to content

Instantly share code, notes, and snippets.

@zerodahero
Created December 20, 2017 15:23
Show Gist options
  • Save zerodahero/c7bc9e69c10d904b05d9a7f60179a608 to your computer and use it in GitHub Desktop.
Save zerodahero/c7bc9e69c10d904b05d9a7f60179a608 to your computer and use it in GitHub Desktop.
Laravel 5.4 Comma Separated Email Validation (Transforming Data)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EmailRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* @inheritDoc
*/
protected function prepareForValidation()
{
$this->replace(['email' => explode(',', $this->email)]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => 'required|bail|array',
'email.*' => 'email'
];
}
public function messages()
{
return [
'email.*' => ':attribute is not a valid email address'
];
}
public function attributes()
{
$attributes = array();
foreach ($this->email as $index=>$email) {
$attributes['email.'.$index] = $email;
}
return $attributes;
}
/**
* This is part of an API which should only
* return JSON
*/
public function wantsJson()
{
return true;
}
}
@aravael
Copy link

aravael commented May 7, 2020

Thx dude

@aravael
Copy link

aravael commented Aug 11, 2020

However I think it's better would be to use 'merge' instead of replace. That's because replace method replaces the incoming data, and if along with email you will have something else, you will replace all your data with email validation only.

$this->replace(['email' => explode(',', $this->email)]);

@zerodahero
Copy link
Author

Yep! Not sure how much of this is still valid considering so much has changed since 5.4. Yes, merge would work better here if you've got more than just email coming it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment