Laravel conditional statement with each() result error - php

Partly confused (still) because the variable $investment_type resulting of "Creating default object from empty value" when I follow this previous question of mine Laravel list() with each() function error with deprecated function.
This is the original code.
$assetsData = ClientPropertyManagement::find($assets_id);
$investmentType = Input::get('investmenttype'.$assets_id);
$legalname = Input::get('legalname'.$assets_id);
$ownership = Input::get('ownership'.$assets_id);
$tic = Input::get('tic'.$assets_id);
$entity_id = Input::get('entity_id'.$assets_id);
foreach($investmentType as $investment_type) {
list($key,$value) = each($legalname);
list($key,$valueOwner) = each($ownership);
list($key,$valueTic) = each($tic);
list($key,$valueEntityId) = each($entity_id);
if($valueEntityId == 0) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($valueEntityId);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $value;
$assetEntity->ownership = $valueOwner;
$assetEntity->ticnum = $valueTic;
$assetEntity->save();
}
Here's what I did in my code.
foreach( $investmentType as $key => $investment_type ) {
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->save();
}

The problem is that $assetEntity isn't created yet, and you are trying to use as an object. To solve that, you need to change the position where you instantiate the object and create the variable $assetEntity:
foreach( $investmentType as $key => $investment_type ) {
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
$assetEntity->save();
}
That way $assetEntity will be created, and then you populate the other attributes.
Also, you may want to use the IoC Container and replace the new ClientEntityManagement with App::make('ClientEntityManagement'). Read more at https://laravel.com/docs/4.2/ioc

Related

PHP add unique User array to newly created array while iterating over Episode authors object

Hi i am iterating over Episodes getting array of authors and inside this loop i want to gather information about each author. But there is problem, i just need the information about each author once.
This is my approatch, but wrong. and the code i am trying to make. Please help. I tried also in_array, and array_filter but without success.
$presentUsers = [];
$pUi = 0;
if ($isAuthor == true){
if ($project->getType() == 1) {
$episodes = $project->getComic()->getComicEpisodes();
foreach ($episodes as $comicEpisode) {
foreach ($comicEpisode->getProject()->getAccount() as $author) {
if ($author->getUser()->getId() == $this->getUser()->getId()) {
$comicEpisode->setIsMine(true);
$comicEpisode->setRevenue($author->getRevenue());
$comicEpisode->setIncome($author->getIncome());
}
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
if (!in_array($presentUsers, ['Id'=>$author->getUser()->getId()]))
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
}
}
}
}else{
die('You are not the author of this project.');
}
Okay i done it like this
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
$found = 0;
foreach ($presentUsers as $presentUser){
if ($presentUser['Id'] == $author->getUser()->getId()){
$found = 1;
break;
}
}
if ($found != 1)
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}

Shorter way in php laravel to load a model in another similar one?

I want to copy every property of the contract model into this another templatecontract model and so on. My code works, but I don't know much about laravel (or php in fact) and my intuition tells me that there must be a better way, or more elegant way.
fill() from Laravel does not get much better. Maybe with a constructor?
Equal tables:
Contract -> TemplateContract
Chapter -> TemplateChapter
Clause -> TemplateClause
public function storeTemplate(ContractCreateRequest $request)
{
DB::beginTransaction();
try
{
$contract = Contract::find($request->input()['type']);
$templatecontract = new TemplateContract();
$templatecontract->id = $contract->id;
$templatecontract->pid = $contract->pid;
$templatecontract->deleted = $contract->deleted;
$templatecontract->sorting = $contract->sorting;
$templatecontract->created_at = $contract->created_at;
$templatecontract->updated_at = $contract->updated_at;
$templatecontract->deleted_at = $contract->deleted_at;
$templatecontract->title = $contract->title;
$templatecontract->description = $contract->description;
$templatecontract->hidden = $contract->hidden;
$templatecontract->contract_type = $contract->contract_type;
$templatecontract->process_type = $contract->process_type;
$templatecontract->tstamp = $contract->tstamp;
$templatecontract->is_english = $contract->is_english;
$templatecontract->usecasetitle = $contract->usecasetitle;
if (Auth::user()) {
$templatecontract->user_id = Auth::user()->id;
}
if($templatecontract->save())
{
$chapter = DB::table('chapter')->where('contract', $templatecontract->id)->get();
if(isset($chapter))
{
foreach ($chapter as $key => $value) {
$templatechapter = new TemplateChapter();
$templatechapter->clause = $value->clause;
$templatechapter->contract = $value->contract;
$templatechapter->created_at = $value->created_at;
$templatechapter->deleted = $value->deleted;
$templatechapter->headlinetype = $value->headlinetype;
$templatechapter->hidden = $value->hidden;
$templatechapter->id = $value->id;
$templatechapter->must = $value->must;
$templatechapter->note = $value->note;
$templatechapter->sorting = $value->sorting;
$templatechapter->title = $value->title;
$templatechapter->tstamp = $value->tstamp;
$templatechapter->updated_at = $value->updated_at;
$templatechapters[] = $templatechapter;
if($templatechapter->save())
{
$clause = DB::table('clause')->where('chapter', $value->id)->get();
if(isset($clause))
{
foreach ($clause as $key => $value) {
$templateclause = new TemplateClause();
$templateclause->id = $value->id;
$templateclause->chapter = $value->chapter;
$templateclause->clausetext = $value->clausetext;
$templateclause->variable = $value->variable;
$templateclause->topic = $value->topic;
$templateclause->deleted = $value->deleted;
$templateclause->selectword = $value->selectword;
$templateclause->shortinfo = $value->shortinfo;
$templateclause->sorting = $value->sorting;
$templateclause->created_at = $value->created_at;
$templateclause->updated_at = $value->updated_at;
$templateclause->hidden = $value->hidden;
$templateclause->tstamp = $value->tstamp;
$templateclause->save();
$templateclauses[] = $templateclause;
}
}
}
}
}
}
//DB::commit();
return response()->success(__('success.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), $templatecontract, 200);
}
catch (Exception $e)
{
return response()->error(__('error.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), 400, $e);
}
}
So almost all of the props from the request matches with the column names. You just need to call the create method of Eloquent model to create a new record and pass key value pair but rather an object. Also, you need not to worry about the extra parameters $contract contains since Laravel will only extract and assign params defined in protected $fillable property of the class.
// cast object to array
$contract = (array) $contract;
$templateContract = TemplateContract::create($contract)

Laravel list() with each() function error with deprecated function

I get a little confuse here on how to alternatively replace the each() function since it was deprecated and I'm aware of that and fixed some of the while( list() = each() ) error case in my project. However, what other option should I use for this case:
foreach($new_id as $new_ids) {
list($key,$valueAddress) = each($address);
list($key,$valueCity) = each($city);
list($key,$valueState) = each($state);
if(isset($_POST['publicOnly'])) {
list($key,$valuePublicOnly) = each($publicOnly);
} else {
$valuePublicOnly = 0;
}
$propertyAddress = PropertyAddressManagement::find($new_ids);
$propertyAddress->address = $valueAddress;
$propertyAddress->city = $valueCity;
$propertyAddress->state = $valueState;
$propertyAddress->publicOnly = $valuePublicOnly;
$propertyAddress->save();
}
You're not using the keys so just get the current value and then move to the next one:
foreach($new_id as $new_ids) {
$propertyAddress = PropertyAddressManagement::find($new_ids);
$propertyAddress->address = current($address);
$propertyAddress->city = current($city);
$propertyAddress->state = current($state);
$propertyAddress->publicOnly = isset($_POST['publicOnly']) ? current($publicOnly) : 0;
$propertyAddress->save();
next($address); next($city); next($state); next($publicOnly);
}
However, if the keys are the same in all of the array then I think really this should work:
foreach($new_id as $key => $new_ids) {
$propertyAddress = PropertyAddressManagement::find($new_ids);
$propertyAddress->address = $address[$key];
$propertyAddress->city = $city[$key];
$propertyAddress->state = $state[$key];
$propertyAddress->publicOnly = isset($_POST['publicOnly']) ? $publicOnly[$key] : 0;
$propertyAddress->save();
}

getting error to display all record in php json

I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work

Laravel 5.4 - Update an existing record

I'm struggling to update an existing record through an Eloquent Model in Laravel 5.4
I have for creating a record that works perfectly fine, I took it and modified it to try and update the record:
public function commitEdit ($char_edit_id)
{
$edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->first();
$edited_character->campaign_id = 1;
$edited_character->character_name = request('characterName');
$edited_character->Race = request('race');
$edited_character->Sub_Race = request('subRaceField');
$edited_character->Class = request('class');
$edited_character->Level = request('level');
$edited_character->Strength = request('strength');
$edited_character->Dexterity = request('dexterity');
$edited_character->Constitution = request('constitution');
$edited_character->Intelligence = request('intelligence');
$edited_character->Wisdom = request('wisdom');
$edited_character->Charisma = request('charisma');
$levelVar = request('level');
if ($levelVar >= 4) {
$edited_character->Proficiency = 2;
} else if ($levelVar >= 8) {
$edited_character->Proficiency = 3;
}
$edited_character->Trained_Skills = request('skillsField');
$edited_character->Languages = request('languagesField');
$edited_character->Hit_Die = 1;
$edited_character->max_HP = request('max-hp');
$edited_character->Alignment = request('alignment');
$edited_character->Armor_Class = request('armor-class');
$edited_character->Initiative = request('initiative');
$edited_character->Speed = request('speed');
$edited_character->Background = request('background');
$edited_character->update();
return redirect('./characters');
That gives this error:
Call to undefined method stdClass::update()
I have tried using save() but I get the same error with save() instead of update()
Thanks in advance c:
Documentation
If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single StdClass object:
$edited_character is a stdClass, no Eloquent model.
You can try this code:
public function commitEdit ($char_edit_id)
{
$edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->update([
'campaign_id' => 1,
'character_name' => request('characterName'),
'Race' => request('race'),
//others property
]);
}
Or create Characters model which will be extends from Illuminate\Database\Eloquent\Model and use save method:
public function commitEdit ($char_edit_id)
{
$edited_character = Characters::where('char_id', $char_edit_id)-first();
//your code with properties
$edited_character->save();
}
You can try this way:
public function commitEdit ($char_edit_id)
{
$edited_character = Characters::find($char_edit_id);
$edited_character->character_name = request('characterName');
$edited_character->Race = request('race');
$edited_character->Sub_Race = request('subRaceField');
$edited_character->Class = request('class');
$edited_character->Level = request('level');
$edited_character->Strength = request('strength');
$edited_character->Dexterity = request('dexterity');
$edited_character->Constitution = request('constitution');
$edited_character->Intelligence = request('intelligence');
$edited_character->Wisdom = request('wisdom');
$edited_character->Charisma = request('charisma');
$levelVar = request('level');
if ($levelVar >= 4) {
$edited_character->Proficiency = 2;
} else if ($levelVar >= 8) {
$edited_character->Proficiency = 3;
}
$edited_character->Trained_Skills = request('skillsField');
$edited_character->Languages = request('languagesField');
$edited_character->Hit_Die = 1;
$edited_character->max_HP = request('max-hp');
$edited_character->Alignment = request('alignment');
$edited_character->Armor_Class = request('armor-class');
$edited_character->Initiative = request('initiative');
$edited_character->Speed = request('speed');
$edited_character->Background = request('background');
if($edited_character->save()){
return redirect('./characters');
}else{
// show error message
}
}

Categories