I have a Laravel app, in which (excel) documents can be entered, which will be parsed to JSON to be uploaded into a MongoDB. I want to adjust my controller so that, projects can't be duplicated. I want to check this on the key 'project_id'. When the 'project_id' in the JSON is unique, the file will be entered in the database. If the 'project_id' is in the database, I would like to return the highest value +1 to tell the user that they could use this 'project_id'. My controller looks like this:
public function upload() {
$file = array('thefile' => Input::file('thefile'));
$rules = array('excel' => 'excel');
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
return Redirect::to('UploadExcelFile')->withInput()->withErrors($validator);
}
else {
if (Input::file('thefile')->isValid()) {
$destinationPath = 'uploads';
$fileName = Input::file('thefile')->getClientOriginalName();
Input::file('thefile')->move($destinationPath, $fileName);
Session::flash('success', 'Upload successfully');
$tmp = exec("python public/scripts/ExcelToJSON3.py $fileName");
// Getting the Project ID from the file that is uploaded
$str = file_get_contents($tmp);
$json = json_decode($str);
$project_id = $json[0]->project_id;
// Opening a connection with the database
$m = new MongoClient();
$db = $m->database;
$collection = $db->test;
// Find a document with the same Project ID
$cursor = $collection->findOne(array("project_id" => $project_id));
if (empty($cursor)) {
$upload = exec("mongoimport --db database--collection test --type json --file " . $tmp . " --jsonArray");
} else {
$highest_projectid = '';
$val = $collection->find(array(), array('project_id' => 1))->sort(array('project_id' => -1))->limit(1);
foreach ($val as $doc)
{
$highest_projectid = implode(',',$doc);
}
return redirect('dashboard/input')->with('status', 'The file which you tried to upload already exist on our database. '.$highest_projectid.' ');
}
return \View::make('UploadExcelFile')->with(array('fileName' => $fileName, 'tmp' => $tmp ));
}
else {
// sending back with error message.
Session::flash('error', 'uploaded file is not valid');
return Redirect::to('UploadExcelFile');
}
}
The output which I am getting as message is:
The file which you tried to upload already exist on our database. 581749cfa0e57d26d69edde9,3
(3 is the highest value)
But the _id value is also printed? Could someone help me?