Reputation: 262
I am fairly new to Laravel.
I am trying to fetch some user data from a remote location as JSON. Here's the code in my Controller to fetch the JSON data.
public function fetch()
{
$url = 'http://example.com'; //fetching data as JSON
$json = json_decode(file_get_contents($url), true);
$this->save($json);
}
I have a User Model class which corresponds to my users table. The email and phone columns are set as unique in the database table.
class User extends Model {
protected $fillable = [
'name',
'email',
'phone'
];
}
The Save function in the same Controller
private function save($json)
{
foreach ($json as $key => $value)
{
$user = User::create([
'name' => $value['name'],
'email' => $value['email'],
'phone' => $value['phone']
]);
}
}
The save works fine as long as the email and phone are unique. If not, it throws a nasty QueryException
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry...
Is there a way to validate the data for uniqueness before trying to save in the database?
Upvotes: 0
Views: 1380
Reputation: 1
i think my answer will help other people coming afterenter image description here in class validation form request if you use it you can use function as call back function at Laravel form request like that and also you can validate json value uniqueness
see exmple at link image its very easy to check validation json uniqueness in database
Upvotes: 0