Getting Error when converting array to a variable in laravel - laravel

I have problem when converting multiple checkbox($request->courses) to a variable(checkbox1).Because I need to insert an array to Database.
public function store(Request $request) {
$customer = new prospect;
$customer->ProspectName = $request->ProspectName;
$customer->NicNumber = $request->NicNumber;
$customer->ContactNumber = $request->ContactNumber;
$customer->ContactAddress = $request->ContactAddress;
$customer->Comments = $request->Comments;
$customer->ReferredThrough = $request->ReferredThrough;
$checkbox1 = $request->courses; //courses is an array from form
$chk = "";
foreach ($checkbox1 as $chk1) {
$chk .= $chk1 . ",";
}
$customer->IntrestedCourses = $chk;
if ($customer->save()) {
echo 'saved successfully';
} else {
echo 'error';
}
}
But I'm getting error!

Related

How to use save() method inside a loop in laravel

My current situation is: I must use save() method to save multiple records using loop. I know insert() will fix my problem but to maintain my code clean I have to use the same code and save() method to insert the record. I create new instance inside the loop but always only last record is being inserted. My code looks like:
public static function save($data)
{
$settings = Settings::instance();
$data['sender_address'] = urldecode($data['sender_address']);
$data['sender_address'] = json_decode($data['sender_address'], true);
extract($data);
$customerFields = ['name', 'mobile', 'alt_mobile', 'district_id', 'area_id', 'address'];
$customerObj = $customer = Customer::where('mobile', $mobile);
if ($customerObj->count()) {
$customer = $customer->first();
} else {
$customer = new Customer;
}
foreach ($customerFields as $customerField) {
if (!empty($$customerField)) {
$customer->$customerField = $$customerField;
}
}
($customerObj->count()) ? $customer->update() : $customer->save();
$order = (isset($order_id) && !empty($order_id) )? Order::find($order_id) : new Order;
$order->sender_address = $sender_address;
$order->branch_id = self::getBranchIdByAreaId($sender_address['area']);
$order->responsible_by = self::getBranchManagerIdByBranchId($order->branch_id);
$order->client_id = $client_id;
$order->customer_id = $customer->id;
$order->delivery_time = $delivery_time;
$deliveryChargeParams = [
'district_id' => $district_id,
'delivery_time' => $delivery_time,
'product_weight' => $product_weight,
'merchant_id' => $client_id,
];
$order->delivery_charge = Utility::getDeliveryCharge($deliveryChargeParams);
$order->vat = Utility::getVat($order->delivery_charge);
if (empty($order_id)) {
$order->status_id = ($role_id == Employee::CLIENT) ?
$settings['tracking']['default_status'] : Order::PACKAGINGDONE;
if (($role_id != Employee::CLIENT)) {
$order->requested = Order::PACKAGINGDONE;
}
}
$order->cash_amount = $cash_amount;
$order->cod_charge = Utility::getCodCharge($cash_amount);
$order->product_weight = $product_weight;
$order->client_reference = $client_reference;
if (empty($order_id)) {
$order->save();
$loggedInUserId = isset($data['fromApp'])?
$data['client_id'] : Auth::getUser()->id;
$order->number = self::orderNumber($order,$loggedInUserId);
$order->update();
} else {
$order->update();
}
if (($role_id != Employee::CLIENT)) {
self::updateDeliveryWithin($order);
}
PaymentAction::update($order);
}
The following method calls this save() method:
function onSave(){
$data = post();
$client_id = (Auth::getUser()->role_id == Employee::CLIENT) ? Auth::getUser()->id : $data['client_id'];
$sender_address = $data['sender_address'];
$file = Input::file('bulk_order');
$filename = time().'-'.rand(2000,99999999).'-'.$file->getClientOriginalName();
$result = $file->move('tempFiles',$filename);
$uploadedFilePath = 'tempFiles/'.$filename;
$contents = $this->csvToArray($uploadedFilePath);
// dd($contents); //exit;
unlink($uploadedFilePath);
$keys = array();
if(count($contents)){
$keys = array_keys($contents[0]);
}else{
throw new ApplicationException('Your Csv file is not in proper Format OR Empty!');
}
$fields = array('client_reference','customer_mobile','customer_alternative_mobile','customer_name','customer_district','customer_area','customer_address','product_weight_in_kg','delivery_time_in_hour','cash_collection');
$diff = array_diff($keys,$fields);
//dd($diff); exit;
if(count($diff)!=0){
throw new ApplicationException('Your Csv file is not in proper Format');
}
// dd($contents); exit;
foreach($contents as $row){
$data['name'] = $row['customer_name'];
$data['mobile'] = $row['customer_mobile'];
if(strlen($data['mobile']) == 10 ){
$data['mobile'] = '0'.$data['mobile'];
}
$data['alt_mobile'] = $row['customer_alternative_mobile'];
if(strlen($data['alt_mobile']) == 10 ){
$data['alt_mobile'] = '0'.$data['alt_mobile'];
}
$data['district_id'] = Utility::getDistrictIdByName($row['customer_district']);
$data['area_id'] = Utility::getAreaIdByName($row['customer_area']);
$data['address'] = $row['customer_address'];
$data['delivery_time'] = $row['delivery_time_in_hour'];
$data['product_weight'] = $row['product_weight_in_kg'];
$data['client_id'] = $client_id;
$data['sender_address'] = $sender_address;
$data['cash_amount'] = $row['cash_collection'];
$data['client_reference'] = $row['client_reference'];
$data['role_id'] = Auth::getUser()->role_id;
OrderAction::save($data);
}
\Flash::success('Bulk Order uploaded Successfully');
return Redirect::to('dashboard/shipments');
}
Is it possible to save multiple records with my approach? Thanks in advance.

Too few arguments to function App\Awe\JsonUtility::addNewProduct(),

i am trying to create a CRUD app and am having trouble, if anyone can point me in the right direction i would be grateful, thank you.
Hi there i am having difficulty using data from the json.
i have used it here and it as worked
class JsonUtility
{
public static function makeProductArray(string $file) {
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product) {
switch($product['type']) {
case "cd":
$cdproduct = new CdProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['playlength']);
$products[] = $cdproduct;
break;
case "book":
$bookproduct = new BookProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['numpages']);
$products[]=$bookproduct;
break;
}
}
return $products;
}
this is my controller
public function index()
{
// create a list.
$products = JsonUtility::makeProductArray('products.json');
return view('products', ['products'=>$products]);
}
this is my route
Route::get('/product' , [ProductController::class, 'index'] );
how can i use this on my controller and what route should i set up to create a product
public static function addNewProduct(string $file, string $producttype, string $title, string $fname, string $sname, float $price, int $pages)
{
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product) {
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $producttype;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($producttype=='cd') $newProduct['playlength'] = $pages;
if($producttype=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents($file, $json))
return true;
else
return false;
}
This is where i am trying to type to code into.
public function create()
{
//show a view to create a new resource
$products = JsonUtility::addNewProduct('products.json');
return view('products', ['products'=>$newProduct], );
}
your function addNewProduct() is expecting 7 parameters when called.
you are getting this error because you cannot provide those parameters that your function is looking for.
in your code above you are passing 'products.json' which is in a string format.
lets assume that it is a JSON data. it will still fail because you are only passing 1 parameter to a function that is expecting 7 parameters.
what you could probably do is change it to
public static function addNewProduct($data)
{
// code here
}
then you can pass your JSON data and then go through each of your json using a loop.

Codeigniter3.x calling multiple stored procedure cache

This is somewhat related to [CodeIgniter active records' problems calling multiple stored procedures
but I am not experiencing a blank page; instead when I am passing my data array to view it seems that the the preceding array also being drag to the view.
model
public function data1($student) {
$year = 1;
$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql, array($course, $student, $year, $sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
public function data2($student) {
$year = 1;
$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
Controller:
$data['data1']=data1 from my model(SP);
$data['data2']=data2 from my model(SP);
View:
foreach($data2 as key => $value ) {
echo ....;
}
Here's the PROBLEM... in the view, I only wanted to output the $data2 but to my surprise $data1 is also being output.
Does anybody else have this issue?
I JUST SOLVE IT.
Model
public function data1($student){
**$this->db->initialize();**
$year = 1;$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
public function data2($student){
**$this->db->initialize();**
$year = 1;$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
controller
$data['data1']=data1 from my model(SP);
**$this->db->close();**
$data['data2']=data2 from my model(SP);

How to pass a message from model to controller codeigniter?

I want to pass a message variable in some conditions to controller from model in codeigniter. But when i am doing this it is printing only "No" everytime.
Model is
public function add_city() {
/* Storing form data into an array */
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
And Controller is
public function addingCity() {
$this->add_model->add_city();
var_dump($msg);
//redirect("/city");
}
Try This also
public function add_city() {
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
On controller redirect message with get method -
public function addingCity() {
$msg = $this->add_model->add_city();
redirect("/city?msg=".$msg);
}
And finally print this message on view page
echo $this->input->get('msg');
You need to assign value to $msg in your controller
public function addingCity() {
$msg=$this->add_model->add_city();// assign
var_dump($msg);
//redirect("/city");
}
Try this
public function add_city() {
$city_name = $this->input->post('city');
$city_overview = $this->input->post('overview');
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='$city_name' ORDER BY id ASC");
$result = $query->result_array()
$count = count($result);
if(empty($count))
{
$msg = "No";
return $msg;
}
else{
$data = array(
'city_name'=>$this->input->post('city'),
'city_overview'=>$this->input->post('overview') );
$this->db->insert('city_tbl', $data);
$msg = "Yes";
return $msg;
}
}
In Controller
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;
}
To pass data to view
public function addingCity() {
$data['msg'] = $this->add_model->add_city();
$this->load->view("filename", $data); # ex $this->load->view("index", $data);
}
Error is in your controller function
Try with this code
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;die;
//redirect("/city");
}

grocery crud rename filename on upload

I need to rename the file on file upload and inserting to the database.
I search for ways but i can't find the right code.
I tried to use callback but it did not work.
Here's my code:
public function home()
{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('blog_post');
$crud->set_field_upload('post_image',UPLOAD_PATH);
$crud->callback_before_upload(array($this,'_before_upload'))
$crud->callback_before_insert(array($this,'rename_img_db'));
$output = $crud->render();
$this->_example_output($output);
}
function rename_img_db($post_array)
{
if (!empty($post_array['post_image'])) {
$ext = end(explode(".",$post_array['post_image']));
$img_name = $post_array['post_image'] = mktime().".".$ext;
$post_array['post_image'] = $img_name;
}
return $post_array;
}
function _before_upload($files_to_upload,$field_info)
{
foreach($files_to_upload as $value) {
$ext = pathinfo($value['name'], PATHINFO_EXTENSION);
$rename = $value['name'];
}
$allowed_formats = array("jpg","gif","png","doc","docx","pdf");
if(in_array($ext,$allowed_formats))
{
return true;
}
else
{
return 'Wrong file format';
}
if ($rename) {
$ext1 = end(explode(".",$rename));
$img_name = $rename = mktime().".".$ext1;
$rename = $img_name;
return $rename;
}
}
I noticed a tipo in your line: $crud->callback_before_upload(array($this,'_before_upload'))
Moreover I had to do something similar and I used the callback_after_insert, then you can get the $primary_key variable and with that update the element, something like this:
$crud->callback_after_insert(array($this, 'rename_img_db'));
public function rename_img_db($post_array,$primary_key)
{
//Here goes the get and set querys with your $primary_key
}

Resources