我想實現的Laravel的新功能「自定義驗證規則」之一,我遇到了以下錯誤:Laravel自定義驗證 - Mailgun API
Object of class Illuminate\Validation\Validator could not be converted to string
我按照此步驟視頻: New in Laravel 5.5: Project: Custom validation rule classes (10/14)
這是一個嘗試Mailgun API的電子郵件驗證工具。
請求簡單的形式:姓,名,公司,電子郵件和消息
這裏是我的代碼:
web.php
Route::post('contact', '[email protected]');
StaticPageController.php
use Validator;
use App\Http\Validation\ValidEmail as ValidEmail;
public function postContact(Request $request) {
return Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
}
ValidEmail.php
<?php
namespace App\Http\Validation;
use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as Guzzle;
class ValidEmail implements Rule
{
protected $client;
protected $message = 'Sorry, invalid email address.';
public function __construct(Guzzle $client)
{
$this->client = $client;
}
public function passes($attribute, $value)
{
$response = $this->getMailgunResponse($value);
}
public function message()
{
return $this->message;
}
protected function getMailgunResponse($address)
{
$request = $this->client->request('GET', 'https://api.mailgun.net/v3/address/validate', [
'query' => [
'api_key' => env('MAILGUN_KEY'),
'address' => $address
]
]);
dd(json_decode($request->getBody()));
}
}
期望
我期待看到這樣的事情:
{
+"address": "[email protected]"
+"did_you_mean": null
+"is_disposable_address": false
+"is_role_address": false
+"is_valid": false
+"parts": {
...
}
}
任何幫助深表感謝。我一直試圖讓這個簡單的例子現在工作兩個多小時。希望有我的經驗的人可以幫忙!
我得到它的工作,你還需要嗎? – user3253002