Laravel -Strange Behaivor. Controller data and Blade data - php

I am returning a value from a variable in my controller but it yields different results when I dd($roles) in my blade view.
public function index()
{
$users = $this->user->getAll(); //DBUserRepository
$roles = $this->user->getRoles($users)
return $roles;
}
Yields correct results
{
id: "1",
username: "Muzikman",
email: "matt.paolini#gmail.com",
password: "$2y$10$Sp7k9Fs0DwFSYHTpWrTWquFmXJpkiKfRIHsjYtdEXTvbdOJwv9AtG",
password_confirmation: "",
confirmation_code: "91f0583ed76c95ebf378648d65d0eac7",
remember_token: "bGmdTchXtilBj41FIazkFS3PDZzr1tVKmTFnMkeeSoD7wpW6hoQ07A42plle",
confirmed: "1",
created_at: "2014-10-19 12:17:55",
updated_at: "2014-10-20 15:07:01",
roles: [
{
id: "12",
name: "Members",
created_at: "2014-10-24 20:45:26",
updated_at: "2014-10-24 20:45:26",
}
]
However, when return $roles from controller to blade it yields different results.
public function index() { $users = $this->user->getAll(); $roles = $this->user->getRoles($users);
return View::view('admin.index', compact('users'))->withRoles($roles); }
Blade var dump {{ dd($roles) }} returns
array (size=2)
0 =>
object(User)[254]
protected 'connection' => null
protected 'table' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
public 'timestamps' => boolean true
protected 'attributes' =>
array (size=10)
'id' => string '1' (length=1)
'username' => string 'Muzikman' (length=8)
'email' => string 'matt.paolini#gmail.com' (length=22)
'password' => string '$2y$10$Sp7k9Fs0DwFSYHTpWrTWquFmXJpkiKfRIHsjYtdEXTvbdOJwv9AtG'
'password_confirmation' => string '' (length=0)
'confirmation_code' => string '91f0583ed76c95ebf378648d65d0eac7' (length=32)
'remember_token' => string 'bGmdTchXtilBj41FIazkFS3PDZzr1tVKmTFnMkeeSoD7wpW6hoQ07A42plle' (
'confirmed' => string '1' (length=1)
'created_at' => string '2014-10-19 12:17:55' (length=19)
'updated_at' => string '2014-10-20 15:07:01' (length=19)
protected 'original' =>
array (size=10)
'id' => string '1' (length=1)
'username' => string 'Muzikman' (length=8)
'email' => string 'matt.paolini#gmail.com' (length=22)
'password' => string '$2y$10$Sp7k9Fs0DwFSYHTpWrTWquFmXJpkiKfRIHsjYtdEXTvbdOJwv9AtG'
'password_confirmation' => string '' (length=0)
'confirmation_code' => string '91f0583ed76c95ebf378648d65d0eac7' (length=32)
'remember_token' => string 'bGmdTchXtilBj41FIazkFS3PDZzr1tVKmTFnMkeeSoD7wpW6hoQ07A42plle' (length=60)
'confirmed' => string '1' (length=1)
'created_at' => string '2014-10-19 12:17:55' (length=19)
'updated_at' => string '2014-10-20 15:07:01' (length=19)
protected 'relations' =>
array (size=1)
Can someone explain what is going on here? Sending the same data object to blade from the controller with different array contents.
Here is the code from my interface:
public function getRoles($users)
{
foreach($users as $user){
$roles[] = \User::with('roles')->find($user->id);
}
return $roles;
}

dd($roles) will spit out the object itself, as see in the second set of output.
{{ $roles }} is going to spit out the object having been run through its toJson() function, resulting in your first set of output.

in this code
public function index()
{
$users = $this->user->getAll(); //DBUserRepository
$roles = $this->user->getRoles($users)
return $roles;
}
you did not dump it, you return the $roles, i think, when you return something and the content is "JSONable", laravel will set the appropriate header and convert the content to JSON. (found in Illuminate\Http\Response)
while the other one
{{ dd($roles) }}
it is same with
<?php var_dump($roles); ?>
which in PHP says that the said function displays structured information about one or more expressions that includes its type and value.

I am just curious. If you are just getting 'roles' column by ::with('roles') function. Why did other info come up in your dd() function result?

Related

Get first array from multiples endpoints async request

I have the guzzle configured which currently uses getAsync with 4 urls promise. The return of this data comes with 2 arrays, of this format below.
My question, how can I separate into two variables, the first being just the first array? In this example, it would be the entire array of sizes 3154 and in the other variable, the entire array of sizes 10297
Guzzle
$requests = [
getenv('apiSavingNew'),
getenv('apiSavingOld'),
];
$promises = (function () use ($requests) {
$client = new Client([
'verify' => false
]);
foreach ($requests as $request) {
yield $client->getAsync($request);
}
})();
$eachPromise = new EachPromise($promises, [
'concurrency' => 2,
'fulfilled' => function (Response $response) {
if ($response->getStatusCode() == 200) {
$request = json_decode($response->getBody());
$firstRequest = // first array here
$secondRequest = // second array here
}
},
'rejected' => function (RequestException $e) {
echo $e->getMessage();
}
]);
$eachPromise->promise()->wait();
Return guzzle promise
array (size=3154)
0 =>
object(stdClass)[11532]
public 'id' => string '57a64bb0-1c6a-11ec-bfd3-173b9227de8c' (length=36)
public 'createdAt' => string '2021-09-23T12:32:40.427Z' (length=24)
public 'data' => string '2021-09-22T00:00:00.000Z' (length=24)
public 'dataFim' => string '2021-10-22T00:00:00.000Z' (length=24)
public 'valor' => string '0.30120' (length=7)
public 'serieTemporalId' => string 'a43978f1-7fd4-4550-9907-106474e64ee4' (length=36)
public 'acumuladoAno' => null
public 'acumulado12Meses' => null
1 =>
object(stdClass)[11539]
public 'id' => string '57a49e00-1c6a-11ec-bfd3-173b9227de8c' (length=36)
public 'createdAt' => string '2021-09-23T12:32:40.416Z' (length=24)
public 'data' => string '2021-09-21T00:00:00.000Z' (length=24)
public 'dataFim' => string '2021-10-21T00:00:00.000Z' (length=24)
public 'valor' => string '0.30120' (length=7)
public 'serieTemporalId' => string 'a43978f1-7fd4-4550-9907-106474e64ee4' (length=36)
public 'acumuladoAno' => null
public 'acumulado12Meses' => null
more elements...
array (size=10297)
0 =>
object(stdClass)[11545]
public 'id' => string '54f70a30-1c6a-11ec-bfd3-173b9227de8c' (length=36)
public 'createdAt' => string '2021-09-23T12:32:35.923Z' (length=24)
public 'data' => string '2021-09-22T00:00:00.000Z' (length=24)
public 'dataFim' => string '2021-10-22T00:00:00.000Z' (length=24)
public 'valor' => string '0.50000' (length=7)
public 'serieTemporalId' => string 'ec940ca2-7da8-4a75-ae7b-d90244797b65' (length=36)
public 'acumuladoAno' => null
public 'acumulado12Meses' => null
1 =>
object(stdClass)[11557]
public 'id' => string '54f3fcf0-1c6a-11ec-bfd3-173b9227de8c' (length=36)
public 'createdAt' => string '2021-09-23T12:32:35.903Z' (length=24)
public 'data' => string '2021-09-21T00:00:00.000Z' (length=24)
public 'dataFim' => string '2021-10-21T00:00:00.000Z' (length=24)
public 'valor' => string '0.50000' (length=7)
public 'serieTemporalId' => string 'ec940ca2-7da8-4a75-ae7b-d90244797b65' (length=36)
public 'acumuladoAno' => null
public 'acumulado12Meses' => null
more elements...
I didnot understood completely what your requirement is? but still I hope that this might help.
You can add the second argument to function in fulfilled as $index and add it in a separate variable for $results empty array.
$results = [];
$requests = [
getenv('apiSavingNew'),
getenv('apiSavingOld'),
];
$promises = (function () use ($requests) {
$client = new Client([
'verify' => false
]);
foreach ($requests as $request) {
yield $client->getAsync($request);
}
})();
$eachPromise = new EachPromise($promises, [
'concurrency' => 2,
'fulfilled' => function (Response $response, $index) {
if ($response->getStatusCode() == 200) {
//$request = json_decode($response->getBody());
$results[$index] = json_decode($response->getBody(), true);
}
},
'rejected' => function (RequestException $e, $index) {
echo $e->getMessage();
}
]);
$eachPromise->promise()->wait();

Save multiple associated entities in one go Cakephp

i've an Order that saves, but the multiple orderlines (a product and total price, quantity) for each order isnt saving together with the order.
Here is the log dump at this stage:
{ "associated": [ "Orderlines", "Payments" ], "Orderlines": [ { "total_cost": "222.44", "total_quantity": "2", "product_variants_id": "34" }, { "total_cost": "154", "total_quantity": "2", "product_variants_id": "33" } ], "users_id": 1, "usersaddress_id": 1, "orderstatus": 0, "date": "2017-09-21T01:53:38+00:00", "last_modified": "2017-09-21T01:53:38+00:00" }
Controller:
$associated = ['Orderlines', 'Payments'];
$order = $this->Orders->newEntity(['associated'=>$associated]);
if ($this->request->is('post')) {
$order = $this->Orders->patchEntity($order, $this->request->getData());
$order->users_id = $this->Auth->user('id');
//Hardcoded the SHU MART stores location because thats all thats gonna get implemented for now
$order->usersaddress_id = 1;
$order->orderstatus = 0;
$order->date = Time::now();
$order->last_modified = Time::now();
//god this is ugly. forgive me for i have sinned
$order->setDirty('users_id', true);
$order->setDirty('usersaddress_id', true);
$order->setDirty('date', true);
$order->setDirty('last_modified', true);
$order->setDirty('orderlines', true);
if ($this->Orders->save($order)) {
$this->Flash->success(__('The order has been saved.'));
return $this->redirect(['controller'=>'orderlines','action' => 'index']);
}
$this->Flash->error(__('The order could not be saved. Please, try again.'));
}
and the form inside the orderline loop:
<?php
echo $this->Form->control('Orderlines.'.$orderLineIndex.'.total_cost',
['label'=>'', 'value'=>$product_total
, 'type'=>'hidden'
]);
?>
<?php
echo $this->Form->control('Orderlines.'.$orderLineIndex.'.total_quantity',
['label'=>'', 'value'=>$item['quantity']
, 'type'=>'hidden'
]);
?>
<?php
echo $this->Form->control('Orderlines.'.$orderLineIndex.'.product_variants_id',
['label'=>'', 'value'=>$item['id']
, 'type'=>'hidden'
]);
?>
Now i've tried it without Orderlines. at the start, and tried saving each orderline individually but it wont save the order id and stuff.
I just want to be able to save it in one go. Something like:
order{ id, x, y, orderlines[[0]{OL1...}[1]{OL2}] }
So i can have as many orderlines in an order and save them all together each time. I think im just missing a small syntax thing, but maybe im not.
public 'associated' =>
array (size=2)
0 => string 'Orderlines' (length=10)
1 => string 'Payments' (length=8)
public 'orderlines' =>
array (size=3)
0 =>
object(App\Model\Entity\Orderline)[349]
public 'total_cost' => float 40.28
public 'total_quantity' => int 1
public 'product_variants_id' => int 679
public '[new]' => boolean true
public '[accessible]' =>
array (size=2)
...
public '[dirty]' =>
array (size=3)
...
public '[original]' =>
array (size=0)
...
public '[virtual]' =>
array (size=0)
...
public '[errors]' =>
array (size=0)
...
public '[invalid]' =>
array (size=0)
...
public '[repository]' => string 'Orderlines' (length=10)
1 =>
object(App\Model\Entity\Orderline)[375]
public 'total_cost' => float 66
public 'total_quantity' => int 2
public 'product_variants_id' => int 55
public '[new]' => boolean true
public '[accessible]' =>
array (size=2)
...
public '[dirty]' =>
array (size=3)
...
public '[original]' =>
array (size=0)
...
public '[virtual]' =>
array (size=0)
...
public '[errors]' =>
array (size=0)
...
public '[invalid]' =>
array (size=0)
...
public '[repository]' => string 'Orderlines' (length=10)
2 =>
object(App\Model\Entity\Orderline)[347]
public 'total_cost' => float 222.44
public 'total_quantity' => int 2
public 'product_variants_id' => int 34
public '[new]' => boolean true
public '[accessible]' =>
array (size=2)
...
public '[dirty]' =>
array (size=3)
...
public '[original]' =>
array (size=0)
...
public '[virtual]' =>
array (size=0)
...
public '[errors]' =>
array (size=0)
...
public '[invalid]' =>
array (size=0)
...
public '[repository]' => string 'Orderlines' (length=10)
public 'users_id' => int 1
public 'usersaddress_id' => int 1
public 'orderstatus' => int 0
public 'date' =>
object(Cake\I18n\Time)[327]
public 'time' => string '2017-09-27T21:12:38+10:00' (length=25)
public 'timezone' => string 'Australia/Melbourne' (length=19)
public 'fixedNowTime' => boolean false
public 'last_modified' =>
object(Cake\I18n\Time)[350]
public 'time' => string '2017-09-27T21:12:38+10:00' (length=25)
public 'timezone' => string 'Australia/Melbourne' (length=19)
public 'fixedNowTime' => boolean false
public '[new]' => boolean true
public '[accessible]' =>
array (size=3)
'*' => boolean true
'id' => boolean false
'users_id' => boolean false
public '[dirty]' =>
array (size=7)
'associated' => boolean true
'orderlines' => boolean true
'users_id' => boolean true
'usersaddress_id' => boolean true
'orderstatus' => boolean true
'date' => boolean true
'last_modified' => boolean true
public '[original]' =>
array (size=1)
'orderlines' =>
array (size=3)
0 =>
object(App\Model\Entity\Orderline)[359]
...
1 =>
object(App\Model\Entity\Orderline)[372]
...
2 =>
object(App\Model\Entity\Orderline)[346]
...
public '[virtual]' =>
array (size=0)
empty
public '[errors]' =>
array (size=0)
empty
public '[invalid]' =>
array (size=0)
empty
public '[repository]' => string 'Orders' (length=6)
Thanks.
So there are 2 answers i got. The first being the really-messy-but-works solution, and the one i found later.
if ($result) {
$orderlinescontroller = new OrderlinesController();
if ($orderlinescontroller->addAllFromCart($result->id)) {
$this->Flash->success(__('The order ' . $result->id . ' has been successfully placed'));
$this->clearUsersCart($this->Auth->user('id'));
so first you save the order, then create an instance of the controller of the associated item you need to save multiple of. Then i created a function that looks at the db/session variables for the cart items to save them with the order.
public function addAllFromCart($order_id)
{
$success = true;
$cart_items = $this->getCartItemsArray();
$saved_ids = [];
foreach ($cart_items as $cart) {
$this->log($cart);
$orderline = $this->makeEntity($order_id, $cart);
$new = $this->Orderlines->save($orderline);
if ($new) {
$this->log('Line saved');
array_push($saved_ids, $new->id);
} else {
$this->log('Line save FAILED');
$success = false;
//if there is a failure, we need to delete the lines that we made - there is a better way, but cake sucks and conventions don't work
foreach ($saved_ids as $id_to_delete) {
$d = $this->Orderlines->get($id_to_delete);
$this->Orderlines->delete($d);
}
}
}
$this->log('WAS ADD ALL FROM CART A SUCCESS? -- ' . $success);
// if ($success) {
// return $this->redirect($this->referer());
// } else {
// return $this->redirect($this->referer());
// }
return $success;
}
`
which altogether is super messy and un-cake-ey but it works. The other solution i found out much later when i revisited a part of adding products, was how it explicitly told save() what associations to save. Hence the below was used.
$result = $this->Orders->save($save, ['associated' => ['Orderlines']]);

Check if row exists and if it doesn't insert data

I have an Eloquent model that is creating new entries into one of my tables. The problem I am having is each time the page runs it is inserting the data over and over. How can I check if that data already exists in that table and if it doesn't exist, then insert that particular data?
foreach($xml as $product) {
//var_dump($product); die;
Order::where('id', '=', $product->reference)->update(
array(
'invoice_id' => $product['orderid'],
'shipped' => $product['shipped'],
'processed' => $product['processed'],
'problem' => $product['problem'],
)
);
$tracking = new OrderTrack();
$tracking->invoice_id = $product['orderid'];
$tracking->shipper = $product->shipping->shipper;
$tracking->shipping_method = $product->shipping->shipping_method;
$tracking->shipping_date = $product->shipping->shipping_date;
$tracking->shipping_cost = $product->shipping->shipping_cost;
$tracking->tracking_number = $product->shipping->tracking_number;
if(!empty($product->shipping->shipping_notes)) {
$tracking->shipping_notes = $product->shipping->shipping_notes;
}
$tracking->save();
echo'done';
}
The OrderTrack is the section of code I am concerned about. It will create a new entry no matter if the row already exists or not.
$xml var_dump
object(SimpleXMLElement)[294]
public 'order' =>
array (size=15)
0 =>
object(SimpleXMLElement)[295]
public '#attributes' =>
array (size=7)
...
public 'reference' => string '3053' (length=4)
public 'reference2' =>
object(SimpleXMLElement)[310]
...
public 'reference3' =>
object(SimpleXMLElement)[311]
...
public 'invoice' =>
object(SimpleXMLElement)[312]
...
public 'order_date' => string '2014-08-14 03:00:06' (length=19)
public 'billing_date' => string '2014-08-14 00:00:00' (length=19)
public 'changed' => string '2014-08-14 13:02:15' (length=19)
public 'sender' =>
object(SimpleXMLElement)[313]
...
public 'receiver' =>
object(SimpleXMLElement)[314]
...
public 'shipping' =>
object(SimpleXMLElement)[315]
...
public 'products' =>
object(SimpleXMLElement)[316]
...
1 =>
object(SimpleXMLElement)[296]
public '#attributes' =>
array (size=7)
...
public 'reference' => string '3054' (length=4)
public 'reference2' =>
object(SimpleXMLElement)[328]
...
public 'reference3' =>
object(SimpleXMLElement)[329]
...
public 'invoice' =>
object(SimpleXMLElement)[330]
...
public 'order_date' => string '2014-08-13 22:00:02' (length=19)
public 'billing_date' => string '2014-08-14 00:00:00' (length=19)
public 'changed' => string '2014-08-14 13:02:20' (length=19)
public 'sender' =>
object(SimpleXMLElement)[331]
...
public 'receiver' =>
object(SimpleXMLElement)[332]
...
public 'shipping' =>
object(SimpleXMLElement)[333]
...
public 'products' =>
object(SimpleXMLElement)[334]
...
Took advantage of firstOrNew
$tracking = OrderTrack::firstOrNew(array('invoice_id' => $product['orderid']));
$tracking->invoice_id = $product['orderid'];
$tracking->shipper = $product->shipping->shipper;
$tracking->shipping_method = $product->shipping->shipping_method;
$tracking->shipping_date = $product->shipping->shipping_date;
$tracking->shipping_cost = $product->shipping->shipping_cost;
$tracking->tracking_number = $product->shipping->tracking_number;
if(!empty($product->shipping->shipping_notes)) {
$tracking->shipping_notes = $product->shipping->shipping_notes;
}
$tracking->save();

Drilling down into JSON with PHP

This is a really simple task, that has me absolutely stumped! I'm pulling back some JSON via CURL and PHP, and attempting to access the data from the below structure:
object(stdClass)[1]
public 'maxResults' => int 43
public 'resultList' =>
array (size=43)
0 =>
object(stdClass)[2]
public '#class' => string '' (length=64)
public 'id' => int
public 'version' => int 0
public 'dateCreated' => string '2014-02-11T18:37:55.835+0000' (length=28)
public 'dateModified' => null
public 'locationId' => int
public 'departmentId' => int
public 'ownerCompanyId' => int
public 'active' => boolean true
public 'userId' => int
public 'userName' => string '' (length=24)
public 'externalCode' => null
public 'employeeDetails' =>
object(stdClass)[3]
...
public 'chargeBandAllocationsIds' =>
array (size=7)
...
public 'personalRateChargeBandId' =>
object(stdClass)[13]
...
public 'employeeGroupIds' =>
array (size=0)
...
public 'isResource' => boolean false
(I've removed some of the values, for privacy reasons)
Now I'm trying to var_dump using var_dump(json_decode($result, false));, however when I try and get into the 'resultList' array using var_dump(json_decode($result['resultList'], false)); I get an illegal string offset error.
$result is the JSON string, your cannot do $result['resultList'] on a string. It only becomes a structure after you json_decode it. However, you're decoding it as object, not array, so this wouldn't work either way.
$data = json_decode($result);
var_dump($data->resultList);
var_dump($data->resultList[0]);
var_dump($data->resultList[0]->id);
foreach ($data->resultList as $employee) {
var_dump($employee->id);
}

PHP object properties are null after instantiation

Here is what is making my brain hurt. First, I know just enough php to explain it in about 5 minutes. I am however fairly versed in object oriented programming. The situation:
I am trying to build a php application to be used as an intranet only tool. My thought is to save the current user in the session. I created a PHP model of my database user table. In the code I am authenticating the user and if the user authenticates then I am creating a User object and saving it in the session. The problem is that the User object is created but all of the properties are null. I have researched on here and php net for some answers and have tried several things but the problem persists. I do not think it is php related, I absolutely think it is something I am doing wrong but just can't put a finger on it. Here is the relevant code sample from the login script. To get here the password must validate, the variable $users is the direct return from the function in my database controller. Since the variable is included in the var_dump the code returning that variable may not be needed. I have tried passing the relevant array elements separately to the constructor, I have tried passing the full array, I have used serialize and unserialize. I have tried to set them using $this->property = $someValue .
if ($hash) {
$current_user = new User($users);
$_SESSION['current_user'] = serialize($current_user);
$current_user = unserialize($_SESSION['current_user']);
var_dump(session_id());
var_dump($users);
var_dump($current_user);
var_dump($_SESSION['current_user']);
}
Here is my constructor:
class User {
public $userid;
public $fname;
public $lname;
public $email;
public $username;
public $function;
public $d_joined;
public $is_internal;
public $is_active;
function __costruct() {
$arguments = func_get_args();
if (!empty($arguments)) {
foreach ($arguments[0] as $key => $property) {
if ($property_exists($this, $key)) {
$this -> {$key} = $property;
}
}
}
}
I have tried _construct($args) and _construct(array($args)) and nothing. Here is the output of the var_dump() calls
string 'cgotecrpu7soqvepoimjo2s116' (length=26)
array (size=1)
0 =>
array (size=20)
'userid' => string '1' (length=1)
0 => string '1' (length=1)
'fname' => string 'First Name' (length=4)
1 => string 'First Name' (length=4)
'lname' => string 'Last Name' (length=8)
2 => string 'Last Name' (length=8)
'email' => string 'email address' (length=21)
3 => string 'email address' (length=21)
'username' => string 'username' (length=9)
4 => string 'username' (length=9)
'password' => string 'hashed password:salt' (length=65)
5 => string 'hashed password:salt' (length=65)
'function' => string '4' (length=1)
6 => string '4' (length=1)
'd_joined' => string '2013-01-14' (length=10)
7 => string '2013-01-14' (length=10)
'is_internal' => string '1' (length=1)
8 => string '1' (length=1)
'is_active' => string '1' (length=1)
9 => string '1' (length=1)
object(User)[2]
public 'userid' => null
public 'fname' => null
public 'lname' => null
public 'email' => null
public 'username' => null
public 'function' => null
public 'd_joined' => null
public 'is_internal' => null
public 'is_active' => null
string 'O:4:"User":9{
s:6:"userid";N;
s:5:"fname";N;
s:5:"lname";N;
s:5:"email";N;
s:8:"username";N;
s:8:"function";N;
s:8:"d_joined";N;
s:11:"is_internal";N;
s:9:"is_active";N;}' (length=162)
So from what I can see, the initial array $users has the correct data. The User object is created in the variable $current_user . However, when I try to access an object property I get an error about accessing an object property from a non-object. It looks like the session variable is not an object, but the $current_user is, even though it has null properties. Can someone point me in the right direction? Thanks.
Your constructor looks wrong for the thing you want to do, I think you should do it this way :
/**
* Constructor set each public values with the ones passed from the passed array
* #param array $userDatas Array containing the user datas
*/
function __construct($userDatas) {
foreach($userDatas as $key => $value) {
if (property_exists($this, $key)) {
$this->$key = $value;
}
}
}

Categories