Laravel 5.6 error: "Creating default object from empty value" - laravel

I'm having this error: Creating default object from empty value in the line with the code:
if ( !$clients->isEmpty() ){ $giftcard->clients_id = $clients[0]->id; }
The whole function:
public function handle($request, Closure $next)
{
if ( empty($request->session()->get('fixedGiftcard')) )
{
$sales = $this->sales->with(['giftcards'])->all();
if ( $sales->isNotEmpty() ){
$found=[];
foreach ($sales as $sale) {
if ( !empty($sale->giftcard_id) ){
$giftcard = $this->giftcards->findBy('id', $sale->giftcard_id);
if ( empty($giftcard->sales_id) ){
$clients = $this->clients->findWhere(['ic' => $sale->ic]);
if ( !$clients->isEmpty() ){ $giftcard->clients_id = $clients[0]->id; }
$giftcard->sales_id = $sale->id;
$giftcard->save();
$found[]=$sale->id;
}else if ( $giftcard->sales_id != $sale->id ){
$sale->giftcard_id = NULL;
$sale->save();
$found[]=$sale->id;
}
}
}
}
$giftcards = $this->giftcards->findWhere([['sales_id','!=', null]]);
if ( $giftcards->isNotEmpty() ){
$found=[];
foreach ($giftcards as $giftcard) {
$sale = $this->sales->findBy('id', $giftcard->sales_id);
// continues
The error message:

This means that $giftcard is not an object and probably even NULL, but by assigning a property to it, it's converted into an object.
In the following lines you create the $giftcard variable and check if the id property is set, but it's possible no result is found and $giftcard is NULL.
$giftcard = $this->giftcards->findBy('id', $sale->giftcard_id);
if ( empty($giftcard->sales_id) ){
This is not an error but a warning, and because of the error reporting level, this message is shown.
You should fix this by checking if $giftcard is valid:
if (!is_null($giftcard)) {
// Your code
}

Related

Is there a way to solve this problem in phpoffice?

Argument 1 passed to PhpOffice\Common\Drawing::pixelsToEmu() must be of the type float, null given, C:\xampp\htdocs\vendor\phpoffice\phppresentation\src\PhpPresentation\Writer\PowerPoint2007\Abstra...
class GeneratePPT extends Controller{
//generateppt
public function generateppt($id){
if(Auth::user()->user_roles == 'superadmin'
|| Auth::user()->user_roles == 'admin'
|| Auth::user()->user_roles == 'officer'){
// do nothing and pass to process
}
else{
return redirect('/')->withError("You don't have permission to download");
}
//convert encrypted id to actutal decrypt value
//get id from route parameter
$id = request()->route('id');
$contracts_id = Crypt::decryptString($id);
$user = ContractDocument::where("contracts_id",$contracts_id)->first();
$contracts = Contract::where("id",$contracts_id)->first();
$shop_branches_id = $contracts->shop_branches_id;
$shop_branches = ShopBranch::where("id",$shop_branches_id)->first();
$family_members = FamilyMember::where("contracts_id",$contracts_id)->get();
// delete old file
if(Storage::exists("public/temp/{$contracts->apply_user_name}.ppt")){
Storage::delete("public/temp/{$contracts->apply_user_name}.ppt");
}
//photo from ContractDocument
$loan_user_photo = $user->loan_user_photo;
$objPHPPresentation = new PhpPresentation();
$layout = $objPHPPresentation->getLayout();
$layout->setCX(8.5, $layout::UNIT_INCH);
$layout->setCY(14, $layout::UNIT_INCH);
//create first table
$currentSlide = $objPHPPresentation->getActiveSlide();
self::createtitle($currentSlide);
self::createfirstTable($currentSlide,9,$contracts,$shop_branches,$family_members,$loan_user_signature,$witness_signature);
// Create user
if ($loan_user_photo != null) {
$currentSlide = $objPHPPresentation->createSlide();
self::createslide($loan_user_photo,$currentSlide,"Borrower ဓါတ်ပုံ");
}
$oWriterPPTX = IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
$savepath = Storage::path("Loan/contract_{$contracts_id}");
$oWriterPPTX->save($savepath. "/contract_{$contracts_id}.ppt");
//update data in daatabase
ContractDocument::where('contracts_id', $contracts_id)->update(["final_all_combined_ppt_contract"=> "Loan/contract_{$contracts_id}/contract_{$contracts_id}.ppt"]);
//move and allow download
Storage::copy("Loan/contract_{$contracts_id}/contract_{$contracts_id}.ppt", "public/temp/{$contracts->apply_user_name}.ppt");
//Storage::download("public/temp/contract_{$contracts_id}.ppt","contract_{$contracts_id}.ppt");
$myFile = storage_path("app/public/temp/{$contracts->apply_user_name}.ppt");
return response()->download($myFile)->deleteFileAfterSend(true);
}

Error:You must specify an orderBy clause when using this function

I am getting the following error while trying to migrate. Actually, I have a lot of data so I used the chunk in laravel.
I am using MongoDB not SQL
** You must specify an orderBy clause when using this function.**
My migration file's up function is is
public function up()
{
ini_set('max_execution_time', 250);
ini_set('memory_limit', '1024M');
$product_array = DB::collection('product')->orderBy('created_at','asc');
$product_array->chunk(20, function($product_array)
{
$cotationPercentForecast=0;
$cotationPercent=0;
$quote_tpl = array();
foreach ($product_array as $key => $value) {
if (isset($value['quote_tpl'])) {
$quote_tpl = $value['quote_tpl'];
$defaultScoreCount = 0;
$realScoreCount = 0;
$forecastScoreCount = 0;
foreach ($quote_tpl as $idxPerimetre => $perimetre) {
if (isset($perimetre['families'])) {
foreach ($perimetre['families'] as $idxFamilies => $family) {
if (isset($family['subfamilies'])) {
foreach ($family['subfamilies'] as $idxSubFamilies => $subfamily) {
if (isset($subfamily['items'])) {
foreach ($subfamily['items'] as $idxitem => $item) {
if (isset($item['criterias'])) {
foreach ($item['criterias'] as $idxcriteria => $criteria) {
if (!isset($criteria['inactive']) || $criteria['inactive'] != 'true') {
$defaultScoreCount++;
if (isset($criteria['real_score'])) {
$realScoreCount++;
}
if (isset($criteria['forecast_score'])) {
$forecastScoreCount++;
}
}
} // FOREACH CRITERIA
} // ISSET CRITERIA ###
} // FOREACH ITEM
} // ISSET ITEM ###
} // FOREACH SUBFAMILY
} // ISSET SUBFAMILY ###
} // FOREACH FAMILY
} // ISSET FAMILY ###
}// FOREACH PERIMETER ##
if ($realScoreCount > 0 && $defaultScoreCount > 0) {
$cotationPercentUn = ($realScoreCount / $defaultScoreCount) * 100;
$cotationPercent = round($cotationPercentUn, 2);
}
if ($forecastScoreCount > 0 && $defaultScoreCount > 0) {
$cotationPercentUnForecast = ($forecastScoreCount / $defaultScoreCount) * 100;
$cotationPercentForecast = round($cotationPercentUnForecast, 2);
}
$results = DB::collection('product')->update(['cotation_percent' => $cotationPercent,'forecast_cotation_percent' => $cotationPercentForecast]);
}
}
});
}
I have gone through many answers here and almost all suggest to use orderBy so I used it. But still getting the error.
i have used
Product::chunk(5, function($product_array){}
Any help is appreciated. Thanks in advance.
This warning is added when Laravel internally uses enforceOrderBy which is defined inside Illuminate/Database/Query/Builder.
Whenever you use chunk on a query builder instantiated by DB facade Illuminate\Database\Query\Builder directly, it would ask you :
You must specify an orderBy clause when using this function.
So it will happen if you are doing :
\DB::table('product')->chunk(10, function($product){
...
});
If you manually add an order by to this, it will not throw the error and will work as expected :
\DB::table('product')->orderBy('created_at')->chunk(10, function($product){
...
});
However, its better to use the Eloquent Model directly like which will not enforce you to add an order by clause manually :
Product::chunk(10, function($product){
...
});
Also there is no method DB::collection(), you can use DB::table() instead if you wish, unless you are using mongodb and not MySQL

How to add another array value in codeigniter using getRecords

The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .

Filtering Eloquent Collection

Trying to filter a collection object down based upon any combination of multiple values. This is as far as I've got. Not happening. Any clues for me?
public function search()
{
$posts = Posting::all();
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($country_id) && $country_id>0 )
{
return $post->where('country_id','=',$country_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($province_id) && $province_id>0 )
{
return $post->where('province_id','=',$province_id);
}
})->values();
return $posts;
}
Any help appreciated.
First off, you should really do a validation for the id being larger than 0, if they were provided. You shouldn't be manually checking that out.
But anyhow, why are you using filter, when you can just directly use Eloquent (I omitted the check for id being bigger than 0):
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$query = Posting::query();
if ( ! empty($type_id)) $query->whereTypeId($type_id);
if ( ! empty($country_id)) $query->whereCountryId($country_id);
if ( ! empty($province_id)) $query->whereProvinceId($province_id);
return $query->get();
First off, you need to return something that makes sense from the closure in your filter:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})
Above returns Eloquent\Builder object, which is evaluated to true, so.. it really doesn't make sense.
This is what you need:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->type_id == $type_id; // bool
}
})
With such code, you will filter the collection. $posts now will hold only those items, that match the statement in that closure.

Indirect modification of overloaded property WatimageComponent::$file has no effect

I am trying to create several thumbs of different sizes using a foreach loop on a resize method.
$sizes = array(
'thumb' => Configure::read('Shop.image_thumb_dimensions'),
'medium' => Configure::read('Shop.image_medium_dimensions'),
'large' => Configure::read('Shop.image_large_dimensions')
);
foreach($sizes as $folder => $size) {
$destFolder = WWW_ROOT. $this->upload_dir . DS . $folder;
if (!file_exists($destFolder)) {
#mkdir($destFolder);
}
$dimensionsArray = explode(',', $size);
$newWidth = $dimensionsArray[0];
$newHeight = $dimensionsArray[1];
$destFile = $destFolder . DS . $fileName;
$resize = $this->__resize($filePath, $destFile, $newWidth, $newHeight);
}
and then the resize function which uses some methods from a component goes like this:
private function __resize($src, $destFile, $newWidth, $newHeight) {
$this->Watimage->setImage($src);
$this->Watimage->resize(array('type' => 'resizecrop', 'size' => array($newWidth, $newHeight)));
if ( !$this->Watimage->generate($destFile) ) {
// handle errors...
return $this->Watimage->errors;
}
else {
return true;
}
}
So this works great for the first image size (the thumb) but thereafter I get the error:
b>Notice</b> (8)</a>: Indirect modification of overloaded property WatimageComponent::$file has no effect [<b>APP/Plugin/Gallery/Controller/Component/WatimageComponent.php</b>, line <b>114</b>
I don't understand what I am doing wrong?? Have spent hours trying to figure this out.
Any illumination on the matter will be greatly appreciated.
This is the method from the component class:
public function setImage($file) {
// Remove possible errors...
$this->errors = array();
try
{
if ( is_array($file) && isset($file['file']) )
{
if ( isset($file['quality']) )
$this->setQuality($file['quality']);
$file = $file['file'];
}
elseif ( empty($file) || (is_array($file) && !isset($file['file'])) )
{
throw new Exception('Empty file');
}
if ( file_exists($file) )
$this->file['image'] = $file;
else
throw new Exception('File "' . $file . '" does not exist');
// Obtain extension
$this->extension['image'] = $this->getFileExtension($this->file['image']);
// Obtain file sizes
$this->getSizes();
// Create image boundary
$this->image = $this->createImage($this->file['image']);
$this->handleTransparentImage();
}
catch ( Exception $e )
{
$this->error($e);
return false;
}
return true;
}
There you go, the initial problem is most probably the unsetting of the WaitmageComponent::$file property
unset($this->file);
https://github.com/elboletaire/Watimage/blob/b72e7ac17ad30bfc47ae4d0f31c4ad6795c8f8d2/watimage.php#L706
After doing so, the magic property accessor Component::__get() will kick in when trying to access the now unexistent WaitmageComponent::$file property, and consequently this results in the warning you are receiving.
Instead of unsetting the variable, it should be reinitialized:
$this->file = array();
And of course it should also be initialized properly:
private $file = array();
You should initialize the property on your class, i think what is going on is you are trying to do something like:
$this->file = $var;
But you need to tell your class what is the $file property is:
class WaitmageComponent extends Component {
public $file = array();
}

Resources