How can I save an array of data into individual rows in Laravel ?
Here's how my UI looks like
once i click the save button in the controller Store function gets the data
public function store(Request $request, $venue, CustomProduct $customProduct)
{
dd($request->Availability);
}
This is how the data looks like
I'm wondering how can i save this to my database ?
This is how my database table looks like
Please suggest me a way that i can save this to my table
Use this example:
$days = ["monday","thursday","wednesday","tuesday","friday","saturday","sunday"];
forach($request->Availability as $key => $value){
CustomProductAvalibility::create([
'day_id' => array_search($key), // array_search($key) returns day id
'starts_at' => $value["start"],
'ends_at' => $value["end"],
'custom_product_id' => '...' // your custom product id
]);
}
Related
i'm using maatwebsite laravel excel to import some data from excel to database. But i want to add some custom ID with incremental value for each row of data.
For now, i'm able to import data with some input value form together.
DataImport file
class DataImport implements ToModel, WithStartRow{
public function model(array $row)
{
return new Tempdat([
'employee_id' => ??? (combination of client_code +1)
'name' => $row[1],
'gender' => $row[2],
'bod' => $this->transformDate($row[3]),
'engagement_code' => request('engagement_code'), //from input form
'client_code' => request('client_code'), //from input form
]);
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
public function startRow(): int
{
return 2;
} }
DataController file
public function ImportExcel(Request $request)
{
$this->validate($request,[
'file' => 'required|mimes:xls,xlsx',
'engagement_code' => 'required',
]);
$file = $request->file('file');
$clientCode = request('client_code');
$engagementCode = request('engagement_code');
$todayDate = date('dFY');
$file_name = $engagementCode.'_'.$todayDate.$file->getClientOriginalName();
$file->move('tempdat',$file_name);
Excel::import(new DataImport, public_path('/tempdat/'.$file_name));
return redirect()->route('dashboard.tempdat.index');
}
What i'd like to do is to add "employee code" which is combination of "client_code" + 1 for every row. for example if client_code is ABCD and there is 3 rows of data imported then the employee_code will be :
ABCD0001
ABCD0002
ABCD0003
...
i'm already searching for count rows but nothing found yet.
Counting rows will bring you problems whenever you remove a single record from the table: You won't be able to insert new rows if your primary employee_id field has UNIQUE key, or you will start inserting duplicated IDs.
Generating the ID in PHP isn't my recomendation either since you could face integrity problems if two records are trying to be stored simultaneously.
I would use the default model's model_id field with autoincrement to make sure that I won't have problems with id assignation, and inmediatly after saving the record I would update the id for the employee_id field which can be also keyed as "primary" in order to be indexed and accessed efficiently.
For example:
class MyModel extends Model {
public function save() {
if(parent::save()) {
$this->update['employee_id' => "ABCD".$this->id];
}
}
}
I haven't still realized how the Excel library you're using handles the model, but I supposed it can be specified somewhere along the process.
I am able to generate incremental id in laravel excel using this:
https://github.com/haruncpi/laravel-id-generator
$config = [
'table' => 'table_name',
'length' => 7,
'field' => 'employee_id',
'prefix' => request('client_code'),
'reset_on_prefix_change' => true,
];
$employee_id = IdGenerator::generate($config);
so, everytime import executed, employee_id will generated on its own following with client_code prefix (ex: ABCD001, ... )
I'm trying to get the last inserted id made from create() eloquent in laravel.
Here's my laravel code
$product = ProductModel::create([
'prodCode' => $prodCode,
'prodTitle' => $dataProducts->prodTitle,
'prodDesc' => $dataProducts->prodDesc,
'attachment' => "images/products/".$attachment,
'prodSize' => $dataProducts->prodSize,
'prodCategory' => $dataProducts->prodCategory,
'prodPrice' => $dataProducts->prodPrice,
'created_by' => auth()->user()->id
]);
I will use this last inserted id for another query with the same function.
Is it possible to do it with this way of saving data, or do I need to convert this code to another efficient way?
The create function of a model returns new record.
Very easily:
$product = ProductModel::create([...]);
// last inserted id
$lastInsertedId = $product->$idField;
Well in this case your are doing right !
use print_r($product->id) to see the last inserted id if the field name is id
I've an existing form which is passing the input data to the model in an array format. $postdata has all the data from the view and sending to model.
Controller:
$inquiry_id = $this->input->post('inquiry_id');
$postdata = $this->input->post();
$this->load->model('Design_model');
$this->Design_model->insertdata($postdata,$inquiry_id);
Model:
function insertdata($data = array(), $inquiry_id){
$sql = $this->db->query("select * from design where inquiry_id='".$inquiry_id."'");
if($sql->num_rows() == 0){
$sql_query = $this->db->insert('design', $data);
}
else{
$this->db->where('inquiry_id', $inquiry_id);
$this->db->update('design', $data);
}
}
Above is working fine. Now, I'd like to add few fields in the view and save in a different database table. Need to exclude the new field values from $postdata array getting saved. Need to find the best approach to do this. I can start with some name for all the new fields, so that we can add any filter if available to exclude from the $postdata.
You can use elements() function from Array helper.
$array = array(
'id' => 101,
'title' => 'example',
'desc' => 'something',
'unwanted' => 'bla bla'
);
$filtered_array = elements(array('id','title','desc'),$array); //you can use this directly to the post data
$this->Design_model->insertdata($filtered_array,$inquiry_id);
You can use array_merge() or array_push() functions to add new fields to the array.
Let's say you have following data
$postdata = array("name"=>"xyz",
"email"=>"xyz#gmail.com",
"age"=>"40",
"gender"=>"Male",
"occupation"=>"Engineer"
);
Of which first 3 records are from old fields and last 2 are from new fields as you saying.
You need to find last index of first set i.e. '3' Now you can do this.
$firstDb = array_splice($postdata,0,3); //here 3 is index we are using to get first 3 records from $postdata
$secondDb = array_slice($postdata,0,3); //here 3 is index we are using to get records from position 3 from $postdata
Output:
$firstDb = array("name"=>"xyz","email"=>"xyz#gmail.com","age"=>"40");
$secondDb = array("gender"=>"Male","occupation"=>"Engineer");
Now you can insert you records as you wish to. Happy coding
I fetch some user data for a view via AJAX:
public function adminFetchUserDXData($id) {
$this->ajax_response(array('data'=>$this->UserDXEntry->find('all', array(
'conditions' => array('user_id' => $id)
))));
}
I use CakePHP 2 and want to convert a timestamp field from several fetched entries to a formatted date before sending it.
How can I do it?
I am developing a simple task management web application using laravel. The requirement states that we need to save the general information such as TaskDate, AssignedTo in a taskinfo table. List of tasks for one specific person are saved in another table called tasks. The tasks table has TaskDetailID (PK), TaskID (FK from the above table), TaskDescription, HoursRequired, etc...
The form allows users to add as many rows as they can which means a person could get assigned unlimited amount of tasks.
My problem now is saving the tasks data in the table. I've successfully saved the data for the taskinfo table, and i can even save the data for the table but only when it's one column.
Here is my store function on TaskInfoController
public function store(Request $request)
{
$validator = Validator::make(
$request->all(),
[
'TaskDate.*' => 'required',
'AssignedTo.*' => 'required',
]
,
[
'TaskDate.*.required' => 'Task Date is required.',
'AssignedTo.*.required' => 'Please assign the task to someone.',
]
);
if ($validator->fails())
{
//redirect errors to mars
}
$taskinfo = new TaskInfo();
$taskinfo->TaskDate = Carbon::createFromFormat("m/d/Y", $request->input('TaskDate'));
$taskinfo->TaskAssignedTo = $request->input('TaskAssignedTo');
// Some more columns here
$taskinfo->Save();
// Now for the tasks table
$tasksbulkinsert = array();
foreach ($request->input('TaskDescription') as $taskdescription)
{
$tasksbulkinsert[] = array('TaskID' => Uuid::uuid4(), 'TaskDescription' => $taskdescription);
}
Task::insert($tasksbulkinsert);
return redirect()->action('TaskInfoController#index')->with('flash_message', 'Successfully Saved!');}
The above code actually works perfectly but i don't know how i can insert the HoursRequired, or any additonal value with the corresponding taskdescription on the tasks table.
I tried a few approaches
having an incremental count such as i++ to know which row index (so to speak) of the taskdescription the query is currently procession, and having another foreach loop with it's own counter for the hoursrequired input and getting the value where the taskdescription's counters is equal to the hoursrequired counter. But it didn't work and even if it did, i don't think having multiple foreach loops for every column is good for performance.
Having different arrays with their own foreach loop to get the values from the inputs and then somehow merge the arrays.
Here is my HTML form
<input class="form-control" name="TaskDescription[]" type="text">
<input class="form-control" name="HoursRequired[]" type="text">
Main Question.
How can I save the TaskDescription and the HoursRequired into the database with one query.
Not so important question
The array validation at the top works but is there a way to have an error message that states the row of the error.
For example, Date is required for row number n.
You can simply:
foreach ($request->input('TaskDescription') as $i=>$taskdescription)
{
$tasksbulkinsert[] = array(
'TaskID' => Uuid::uuid4(),
'TaskDescription' => $taskdescription,
'HoursRequired' => $request->input('HoursRequired')[$i]
);
}
For your second question:
$messages = [];
foreach($this->request->get('TaskDescription') as $key => $val)
{
$messages['TaskDescription.'.$key.'.required'] = 'TD is required for row $key';
$messages['some_field.'.$key.'.some_rule'] = 'some_field custom message on row $key';
}
$validator = Validator::make(
$request->all(),
[
'TaskDate.*' => 'required',
'AssignedTo.*' => 'required',
]
,
$messages;