I have this problem in uploading my csv to my database (SQL). I am using Maatwebsite... And here's is my controller:
class UploadCSV extends Controller
{
public function store(Request $request){
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['s_id' => $value->id,
'school_name' => $value->sname,
'region' => $value->reg,
'province' => $value->prov,
'municipality' => $value->mun,
'division' => $value->div,
'district' => $value->dis,
'enrollment_sy_2014_2015' => $value->enrolled,
'mooe_in_php_for_fy_2015' => $value->mooe,
'latitude' => $value->lat,
'longitude' => $value->lng
];
}
Map::insert($arr);
dd('Insert Record successfully.');
//return json_encode($arr);
}
}
dd('Request data does not have any files to import.');
}
Which gives me this endless error message:
The CSV contains only 200+ rows. Any help would be appreciated. Thanks in advance :))
Maybe try something like this, create new Model (assuming Map is the name of your Model and save():
<?php
class UploadCSV extends Controller
{
public function store(Request $request){
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$entry = new Map;
$entry->s_id = $value->id;
$entry->school_name = $value->sname;
$entry->region = $value->reg;
$entry->province = $value->prov;
$entry->municipality = $value->mun;
$entry->division = $value->div;
$entry->district = $value->dis;
$entry->enrollment_sy_2014_2015 = $value->enrolled;
$entry->mooe_in_php_for_fy_2015 = $value->mooe;
$entry->latitude = $value->lat;
$entry->longitude = $value->lng;
$entry->save();
}
}
}
dd('Request data does not have any files to import.');
}
}
Related
I am coding in Laravel, How can I pass variable to one function to another function in Controller,
In controller file I have 2 functions like this
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
$interview = $request->get('interview');
$assignto = $request->get('assignto');
$dateTime = $request->get('dateTime');
$note = $request->get('note');
$interviewDetails = ([
'interview' => $interview,
'assign_to' => $assignto,
'date_time' => $dateTime,
'note' => $note,
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $candidateName], function ($message) use ($assignto, $name) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$name);
});
return redirect('list-candidate');
}
I want to use $candidateName and $name in assignInterview() function from hiringEmployee() function.
How can I do it?
You won't be able to use the $name and $candidateName directly from the other function as they look like they are for two different requests, however, it looks like you're saving that data to database when you're creating a new EmployeeHire in your hiringEmployee() method so you should already have access to that information in your assignInterview() method:
$assignInterview = EmployeeHire::find($id); // this is where you loading the model
$candidateName = $assignInterview->candidateName;
$name = $assignInterview->file;
In your situation , you can use two approach:
#1
Use Session Variable as below:
Session::put('candidateName', $candidateName);
Then:
$value = Session::get('candidateName');
#2
Use class attribute:
class acontroller extends Controller
{
private $classCandidateName;
}
You can try something like this:
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
if(is_null($assignInterview)){
return redirect()->back()->withErrors(['Error message here']);
}
$interviewDetails = ([
'interview' => $request->get('interview'),
'assign_to' => $request->get('assignto'),
'date_time' => $request->get('dateTime'),
'note' => $request->get('note'),
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $assignInterview->candidateName], function ($message) use ($assignto, $assignInterview->file) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$assignInterview->file);
});
return redirect('list-candidate');
}
Please, you should to be careful with find($id). If it is a null, you will get an error.
Have fun!
I am trying to increase the speed of my queries in Laravel 5.7 and I have the call down to ~2.5 seconds. I am trying to figure out more ways to make it faster and if I could get some help I'd greatly appreciate it.
Thanks
How my data is structured:
Function(Controller):
public function getUserDataTmp(Request $request) {
$input = file_get_contents("php://input");
$request = json_decode($input);
if ($this->authTokenAccess($request) == true) {
$bottomWords = bottom_exterior_word::select('word','sentence','sequence','id','group_id')->where('user_id','=', $request->id)->get();
$emergencyWords = left_exterior_word::select('word','sentence','sequence','id')->where('user_id','=', $request->id)->get();
foreach($bottomWords as $tmp => $key) {
$group_id = $key->group_id;
$bottomWords->user_id = $request->id;
$bottomWords[$tmp]->words = $key->getMainWords($group_id, $request->id);
}
foreach($emergencyWords as $key => $word) {
$emergencyWords[$key]->image = imageModel::select('base64','id')->where('emergency_id','=', $word->id)->first();
}
$data = [
'data' => [
'return' => 'success',
'code' => 'VEDC001',
'response' => 'Successfully Gathered Words',
'main_categories' => $bottomWords,
'emergency_words' => $emergencyWords
]
];
return(json_encode($data));
}
}
getMainWords Function(bottom_exterior_word model):
public function getMainWords($group_id, $id)
{
// return("TEST");
$words = \App\main_word::select('id','group_id','sentence','sequence','word')->where('group_id','=', $group_id)->where('user_id','=', $id)->get();
foreach ($words as $key => $word) {
$words[$key]->image = Image::select('base64','id')->where('word_id','=', $word->id)->first();
}
return $words;
}
Start by refactoring so that you dont query inside a foreach loop
foreach($bottomWords as $tmp => $key) {
$group_id = $key->group_id;
$bottomWords->user_id = $request->id;
$bottomWords[$tmp]->words = $key->getMainWords($group_id, $request->id);
}
I would change the getMainWords function to accepts an array of group id's and use the whereIn clause:
The whereIn method verifies that a given column's value is contained
within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
Same treatment for this loop.
foreach($emergencyWords as $key => $word) {
$emergencyWords[$key]->image = imageModel::select('base64','id')->where('emergency_id','=', $word->id)->first();
}
In general minimizing the NUMBER of queries will improve response time.
Old post, would just like to update it though. Since I have first posted this, I have learned a lot more about Laravel and am a lot more experienced with it.
Here is my new function and solution:
Controller:
public function data(Request $request)
{
return response()->success(
[
'emergencywords' => EmergencyWord::with('image')->whereUserId($request->user()->id)->get(),
'categorywords' => CategoryWord::with(['image','words.image'])->whereUserId($request->user()->id)->get(),
]
);
}
Category Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
public function words()
{
return $this->hasMany('App\MainWord','category_words_id','sequence');
}
Emergency Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
Main Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
I am having trouble saving this into database. When I submit my data into database it will only show name_of_bear and all the many relationship stuff(type_of_fish) but not the type_of_bear
Can someone explain to me why it can't work and also maybe give me an example on how it should be done. Thank you
Controller: (this works)
public function submit(Request $request)
{
$fishType= $request->input('type_of_fish');
$Name = $request->input('Name');
$bearType = $request->input('bearType');
$bear = Bear::create(['Name' => $request->input('name_of_bear')]);
$bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);
return ('thank you');
}
But if I were to do this:
Controller : (doesn't work)
public function submit(Request $request)
{
$fishType= $request->input('type_of_fish');
$Name = $request->input('Name');
$bearType = $request->input('bearType');
$bear = Bear::create(['Name' => $Name]);
$bear = Bear::create(['bearType' => $bearType]); --> doesn't work if add in this
$bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);
return ('thank you');
}
or this:
Controller: (doesn't work)
public function submit(Request $request)
{
$fishType= $request->input('type_of_fish');
$Name = $request->input('Name');
$bearType = $request->input('bearType');
$bear = Bear::create(['Name' => $Name], ['bearType' => $bearType]); --> doesn't work
$bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);
return ('thank you');
}
You can add it like this
$bear = Bear::create(['Name' => $Name , 'bearType' => $bearType]);
full code:
public function submit(Request $request)
{
$fishType= $request->input('type_of_fish');
$Name = $request->input('Name');
$bearType = $request->input('bearType');
$bear = Bear::create(['Name' => $Name , 'bearType' => $bearType]);
return ('thank you');
} // removed extra }
For further information you can read documentation
You can just use:
$bear = Bear::create(['Name' => $Name, 'bearType' => $bearType]);
For more info, visit this link.
You can insert data like this:
public function submit(Request $request)
{
$data = array();
$data['type_of_fish']= $request->type_of_fish;
$data['Name'] = $request->Name;
$data['bearType'] = $request->bearType;
$bear = Bear::create($data);
return ('thank you');
}
For more information read Documentation
I would do it like this, assuming that post array keys matches column names.
$bear = Bear::create($request->all()->except(['_token', 'type_of_fish']));
I'm trying to save relations in third table 'Relations'. Here's code:
Controller save action:
$relations = $_POST['VideoCaptions']['countries'];
$model->attachBehavior('ManyToManyRelationBehavior', array(
'class' => 'ManyToManyRelationBehavior',
'modelNameRelation' => 'Relations',
'firstField' => 'video_captions',
'secondField' => 'video_countries',
'relationList' => $relations,
));
ManyToManyRelationBehavior class afterSave action:
if (is_array($this->relationList)){
$model_ = $this->modelNameRelation;
$model_::model()->deleteAll("first_field = :firstField AND first_field_value = :firstFieldValue AND second_field = :secondField", array(
":firstField" => $this->firstField,
":firstFieldValue" => $this->owner->id,
":secondField" => $this->secondField
));
foreach ($this->relationList as $value){
$model_ = new $this->modelNameRelation;
$model_->first_field = $this->firstField;
$model_->first_field_value = $this->owner->id;
$model_->second_field = $this->secondField;
$model_->second_field_value = intval($value);
if (!$model_->save()) return false;
}
}
return true;
var_dump($model_) returns that model exists, but $model->save() doesn't save any data in table 'Relations'. I can't understand why. Can anyone help?
What are the validations you set up for this "modelNameRelation"? You should try the insert() method instead of save() and check whether it will work or not? Save first validates then call insert() or update() method.
SOLVED:
foreach ($this->relationList as $value){
$model = new $this->modelNameRelation;
$model->first_field = $this->firstField;
$model->first_field_value = $this->owner->id;
$model->second_field = $this->secondField;
$model->second_field_value = intval($value);
Yii::app()->db->createCommand()->insert($model->tableName(), $model->attributes);
}
Im currently making a google maps component for Joomla 2.5 using Gmaps3, im at the point where it populates the map with markers, but my foreach loop is only returning one object.
Code below:
My View.json.php:
<?php
defined( '_JEXEC' ) or die;
jimport( 'joomla.application.component.view');
class LocateViewBranches extends JView
{
public function display($tpl = null)
{
$branch = $this->get('Branches');
foreach ($branch as $row) {
$response = array(
'lat' => $row->branch_latitude,
'lng' => $row->branch_longitude,
'data' => array(),
);
$response['data'][] = array(
'city' => $row->branch_city,
);
}
echo json_encode($response);
}
}
and then in my Model;
<?php
defined( '_JEXEC' ) or die;
jimport('joomla.application.component.model');
class LocateModelBranches extends JModel
{
public function getBranches()
{
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__branches');
$query->where("published = 1");
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
}
Please shout if you guys need more code, but i think those are the two key files.
Thanks in advance
I've tidied up your display function. It will echo a multidimensional array in json format:
public function display($tpl = null)
{
$responses = array(); // assign each row to this array
$branch = $this->get('Branches');
foreach ($branch as $row)
{
// append row data to $responses array
$responses[] = array(
'lat' => $row->branch_latitude,
'lng' => $row->branch_longitude,
'data' => array(
'city' => $row->branch_city
),
);
}
echo json_encode($responses);
}
I haven't tested it but it should be what you need.