Hi i am kind of new to laravel.
I have try to build some sort of lead menagment CRM with laravel.
that goes to google sheet api, and get all the record from there every time the page refresh.
and the problem is that is create duplicate records,
and if use ->unique()
its fatal error "duplicate entry" on the records that already exist from the previus refresh.
what i want is a way to save only the records that not exist
Schema
Schema::create('leads', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('name');
$table->string('email')->unique();
$table->string('tel');
$table->string('type')->nullable();;
$table->string('status')->nullable();;
$table->string('reject')->nullable();;
$table->timestamps();
});
Controller
public function index(Request $request, User $user)
{
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=../att-sheets-b5343f28dd39.json');
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Drive::DRIVE);
$driveService = new Google_Service_Drive($client);
// List Files
// $response = $driveService->files->listFiles();
// Set File ID and get the contents of your Google Sheet
$fileID = '1okqjGbGDnbzJbXDwZ1A6RHJ3LddyL6fGMZWnq88xUiw';
$response = $driveService->files->export($fileID, 'text/csv', array(
'alt' => 'media'));
$content = $response->getBody()->getContents();
// Create CSV from String
$csv = Reader::createFromString($content, 'r');
$csv->setHeaderOffset(0);
$records = $csv->getRecords();
// Create an Empty Array and Loop through the Records
$newarray = array();
foreach ($records as $value) {
$newarray[] = $value;
}
foreach ($newarray as $data) {
auth()->user()->leads()->create([
'name' => $data['your-name'],
'tel' => $data['your-tel'],
'email' => $data['your-email']
]);
}
return view('leads.index', compact('newarray'));
}