Requesting solution for laravel 8 project - laravel

I'm an elementary web developer, I'm facing a problem. Please help me solve this. I'm creating both row and column dynamic. for save() is fine. But for update, only name is updated and other item
quantities cannot. Here is my codes.
//for save()
public function stockAdd(Request $request)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$user_id = Auth::user()->user_id;
$stock_id = random_int(100000, 999999);
$stocks = new Stocks();
$stocks->stock_id = $stock_id;
$stocks->owner_id = $user_id;
$stocks->stock_name = request()->stock_name;
$stocks->my_stock = 0;
$stocks->disable = 0;
$stocks->save();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
$stockitems = new StockItems();
$stockitems->stock_id = $stock_id;
$stockitems->product_id = $product->product_id;
$stockitems->owner_id = $user_id;
if(request()->$product_id > 0){
$stockitems->count = request()->$product_id;
}else{
$stockitems->count = 0;
}
$stockitems->save();
}
}
}
return redirect()->back()->with('successAddMsg','Successfully Added');
}
//for update()
public function stockUpdate(Request $request, $id)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$stock = Stocks::findOrFail($id);
$stock->stock_name = request()->stock_name;
$stock->my_stock = 0;
$stock->disable = 0;
$stock->update();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
//dd($product_id);
$stockitemitems = DB::table("stock_items")->select("*")->where("owner_id",Auth::user()->user_id)->where("stock_id",$stock->stock_id)->get();
$stockitems->count = $request->input($product_id);
$stockitems->update();
}
}
}
return redirect(route('user.stock-list'))->with('successAddMsg','Successfully Added');
}
The problem shows like this "Creating default object from empty value"

Related

Can not use seession laravel

I initialize session('idUser') on successful login. But it is always null when using http get.And Auth::id() is always null as well.
class CartService {
public function getAll($orderBys = [], $limit = 2) {
$idCurrent = session('idUser'); // => null
//$idCurrent = Auth::id(); => null
$query = Cart::query() -> where('user_id',$idCurrent);
if($orderBys){
$query->orderBy($orderBys['column'], $orderBys['sort']);
}
return $query-> paginate($limit);
}
}
//Call API (127.0.0.1:8000/api/cart)
public function index(Request $request)
{
$carts = Http::get("http://127.0.0.1:8000/api/cart");
$carts = json_decode($carts, true);
$cartArr = $carts['cartArr'];
//convert
$cart = array();
for($i = 0; $i < count($cartArr); $i++)
{
$object = new Cart();
foreach ($cartArr[$i] as $key => $value)
{
$object->$key = $value;
}
array_push($cart,$object);
}
dd($cart); // => result = []
}

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.

$this->pagination->create_links(); returning nothing

Link for pagination not working
This is my controller.
Here Is my code. What's wrong in this.
Here links are not Initialize. Tell me the correct solutions
The create_links(); the function seems to not be working. I don't get any errors, but it just returns a blank string. I'm aware the documentation says http://codeigniter.com/user_guide/libraries/pagination.html The create_links() function returns an empty string when there is no pagination to show. but so how do I fix that? Thanks you!
public function Index()
{
$this->load->model('Testmodel');
$conf = array();
$conf['base_url'] = base_url()."index.php/user/view";
$conf['total_rows'] = $this->db->get('user')->num_rows();
$conf['per_page'] = 5;
$conf['use_page_numbers'] = TRUE;
$conf['num_links'] = 2;
$conf['cur_tag_open'] = ' <a class="current">';
$conf['cur_tag_close'] = '</a>';
$conf['next_link'] = 'Next';
$conf['prev_link'] = 'Previous';
if($this->uri->segment(3)){
$page = ($this->uri->segment(3)) ;
}
else{
$page = 0;
}
$data['records'] = $this->Testmodel->fetch_data($conf['per_page'], $page);
$this->pagination->initialize($conf);
$data['links'] = $this->pagination->create_links();
}
Model Code:
public function fetch_data($limit, $start) {
$this->db->select('user.*,country.countryName,state.stateName,city.cityName');
$this->db->from('user');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;

Laravel foreach save data

I have a loop for create or update data like below
foreach ($goods_list as $goods) {
$w_estim_mp = WEstimMp::where('event_seq', \LoginInfo::event_data()['event_seq'])
->where('goods_seq', $goods['goods_seq'])
->first();
if (!isset($goods['note'])) {
$goods['note'] = '';
}
if (!isset($w_estim_mp)) {
$w_estim_mp = new WEstimMp;
$w_estim_mp->event_seq = \LoginInfo::event_data();
$w_estim_mp->goods_seq = $goods['goods_seq'];
$w_estim_mp->mp_item_category = $mp_item_category;
}
$w_estim_mp->num = $goods['num'];
$w_estim_mp->note = $goods['note'];
$w_estim_mp->proc_flg = 2;
$now = (new \Carbon\Carbon())->format('Y-m-d H:i:s');
$w_estim_mp->update_dtime = $now;
$w_estim_mp->save();
}
I don't know why i can update only last value of $goods_list.
Help me T.T Thank you!
You can use array_pop to remove the last element and array_push to insert a new element. Follow an example:
<?php
$initial_array = [1,2,3];
function change_last($array, $value) {
$removed_element = array_pop($array);
array_push($array, $value);
return $array;
}
$changed_array = change_last($initial_array, 4);
print_r($changed_array);
?>
and here a live example:
https://tech.io/snippet-widget/ZfEzgjj
I resolved my question!
I don't know why but i work, finnaly, after i changed to
foreach ($goods_list as $goods) {
$goods_seq = $goods['goods_seq'];
$num = $goods['num'];
$w_estim = WEstimMp::where('event_seq', $event_seq)
->where('goods_seq', $goods_seq)
->first();
if (!isset($goods['note'])) {
$goods['note'] = '';
}
$now = (new \Carbon\Carbon())->format('Y-m-d H:i:s');
if (!isset($w_estim)) {
$w_estim = new WEstimMp;
$w_estim->event_seq = $event_seq;
$w_estim->goods_seq = $goods_seq;
$w_estim->mp_item_category = $mp_item_category;
$w_estim->num = $num;
$w_estim->note = $goods['note'];
$w_estim->proc_flg = 2;
$w_estim->update_dtime = $now;
$w_estim->save();
} else {
$w_estim = WEstimMp::where('event_seq', $event_seq)
->where('goods_seq', $goods_seq)
// ->first()
->update([
'num' => $num,
'note' => $goods['note'],
'proc_flg' => 2,
'update_dtime' => $now,
]);
}

Picture not uploading to database but saving in folder

public function array_from_post($fields) {
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
public function save($data, $id = NULL) {
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
On save this code returns column picture cannot be null. When i do the direct method without using the method array_from_post(), data is saved in the database but i can not save a post to be published at a future date.

Resources