Unable to fetch data from Laravel Eloquent Relationships - php

i wanted access the value of content_type_id .i tried like $courseChapters['chapter_content']['content_type_id'] , $courseChapters['content_type_id'] , $courseChapters[0]['content_type_id'] & $courseChapters['chapterContent']['content_type_id'].All these shows the error ErrorException: Undefined index: content_type_id . I also tried everything in the foreach loop i've commented below. Nothing works. Can someone tell me how to fix this?
/*foreach($courseChapters as $key){
// $contentTypeId=$key->first(); //Call to a member function first() on int
// $contentTypeId=$key->first()->chapter_content; //Call to a member function first() on int
// $contentTypeId=$key['chapter_content']['content_type_id']; //error - Illegal string offset
// $contentTypeId=$key[0]['content_type_id']; ////error - Illegal string offset
// $contentTypeId=$key['content_type_id']; //error - Illegal string offset 'content_type_id'
}*/
$courseChapters = courseChapter::with(['chapterContent' => function ($q) use ($id) { $q->where('course_chapter_id', $id)->select('course_chapter_id','file_id','content_type_id');}])
->select('id','courseId', 'chapter_title', 'isExam', 'points')
->get()->toArray()[0];
Heading ## dd($courseChapters); shows array like given below:
array:6 [
"id" => 4
"courseId" => 24
"chapter_title" => "chapter1"
"isExam" => false
"points" => 8
"chapter_content" => array:1 [
0 => array:3 [
"course_chapter_id" => 4
"file_id" => 1
"content_type_id" => 1
]
]
]

Like this to access the first
echo $courseChapters['chapter_content'][0]['content_type_id'];
or like this to access all of them
foreach ($courseChapters['chapter_content'] as $chapter) {
echo $chapter['content_type_id'];
}

Related

php Illegal offset while appending to array

So I'm trying to change an array that I have;
+rows: array:31 [▼
0 => array:2 [▼
0 => "20190101"
1 => "5"
]
1 => array:2 [▼
0 => "20190102"
1 => "15"
]
2 => array:2 [▼
0 => "20190103"
1 => "17"
]
To modify the index 0 of each row to a Carbon DateTime Object for further processing.
Now I'd like to have a json output, but I currently even can't get rid of the Illegal offset type error....
The code I'm using to retreive the data (from GoogleAnalytics) is the follwing:
$get_stats = Analytics::performQuery(
Period::create(Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()),
'ga:users',
[
'dimensions' => 'ga:date',
'samplingLevel' => 'HIGHER_PRECISION',
'include-empty-rows' => true
]
);
This returns alot of code, but I just grab the $get_stats->rows (see above for that output).
I then make a new array, defined as $stats = [];.
A loop iterates over the $get_stats->rows, so I can 'modify' the data in the array and append it to the newly created array.
foreach ($get_stats->rows as $value)
{
$stats[] = [Carbon::createFromFormat('Ymd', $value[0]) => $value[1]];
}
However I get (always) the Illegal offset type error, on the line with $stats[] = [Carbon::createFromFormat('Ymd', $value[0]) => $value[1]];
Can someone help me out with this? I have no clue why it does this, when I try to append an array to an array. I tried array_push(), gives the same issue, also array_merge has the same issue...
This is happening because Carbon::createFromFormat('Ymd', $value[0]) returns a Carbon object, and objects are not valid array indexes. I'm not sure what you're trying to achieve by doing this conversion on the key, it seems a simple
$stats[] = [$value[0] => $value[1]];
or even
$stats[$value[0]] = $value[1];
might be more useful to you. You can always do the conversion to a Carbon object when you want to display the data.

Laravel - Trying to get property of non-object - PHP

I am currently trying to learn Laravel and PHP in general.
I need to be able to import an Excel file, then get the data from that file. Currently, the import part works and I can see the data from the file. However, I am having trouble accessing the data.
I've read about the toArray() function in Laravel, and is using that as below:
$data = Excel::load($path, function($reader) {})->skipColumns(2)->get();
$data = $data->toArray();
foreach ($data as $key => $value) {
//We only need some of the available data.
echo $value->next_milestone_desc_cur._comp._incl_rltd;
echo $value->shipment_id;
}
Above code gives me below error:
Trying to get property 'next_milestone_desc_cur' of non-object
Below is an output from the array, which I have generated using dd($value):
array:543 [▼
0 => array:20 [▼
"next_milestone_desc_cur._comp._incl_rltd" => "005. DK - Add DropMode/Local Trp Org in Pickup Tab"
"milestone_cur._comp._sequence_no" => "005"
"cur._comp._export_validation" => "NOT OK"
"shipment_id" => "SBRY0162091"
"consol_id" => "CDK327188" ]
1 => array:20 [▼
"next_milestone_desc_cur._comp._incl_rltd" => "005. DK - Add DropMode/Local Trp Org in Pickup Tab"
"milestone_cur._comp._sequence_no" => "005"
"cur._comp._export_validation" => "NOT OK"
"shipment_id" => "SBRY0162124"
"consol_id" => "CDK327221"
]
What am I doing wrong here? I have also tried
echo $value[0]->next_milestone_desc_cur._comp._incl_rltd;, however this doesn't work either.
You are trying to access an array as an object hence your error and to address you second point, you need to use a nested loop to then access the sub-array.
Your array looks something like this:
$array = [
0 => [
0 => [
'test' => 'value'
],
1 => [
'test' => 'something'
]
],
1 => [
0 => [
'test' => 'value'
],
1 => [
'test' => 'something'
]
]
];
You need the following loop:
foreach ($array as $key => $nested) {
foreach ($nested as $nested_value) {
// You have access to your inner arrays.
echo $nested_value['test'] . ' | ';
}
}
Where your nested loops $nested would be $value.
Live Example
Repl
Your output from dd($value) shows that $value is an array. So you cannot use arrow notation that is for objects. Change these lines:
echo $value->next_milestone_desc_cur._comp._incl_rltd;
echo $value->shipment_id;
To:
echo $value[0]["next_milestone_desc_cur._comp._incl_rltd"];
echo $value[0]["shipment_id"];

Php key is undefined, but there is key

I am making my own array from another one, using email field as key value. If there is more results with same email I am amking array_push to existing key.
I am getting always data in my array (with email) and here is the example
Input data
Example data
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}
Error
I am getting error Undefined index: test#test.com and if I debug my array, there is key with value of 'test#test.com', so key is defined (!)
so var $curVal key is undefined
Result
So the goal of foreach is to filter all objects in array with same email, here is the example:
$data = [
'test#test.com' => [
0 => {data},
1 => {data},
...
],
'bla#test.com' => [
0 => {data},
1 => {data},
...
],
];
this line $curVal = $data[$products->custom_product_email]; is useless and is the one provoking the error: you just initialized $data as an empty array, logically the index is undefined.
You should test directly if (!isset($data[$products->custom_product_email])) {
Then explanation: there is a fundamental difference between retreiving the value of an array's index which is undefined and the same code in an isset. The latter evaluating the existence of a variable, you can put inside something that doesn't exist (like an undefined array index access). But you can't store it in a variable before the test.
Did you not see the error message?
Parse error: syntax error, unexpected '{' in ..... from this code
$saved_data = [
0 => {'custom_product_email' => 'test#test.com',...},
1 => {'custom_product_email' => 'test#test.com',...},
2 => {'custom_product_email' => 'bla#test.com',...},
3 => {'custom_product_email' => 'bla#test.com',...},
...
];
Change the {} to [] to correctly generate the array.
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Your next issue is in this code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
// ^^^^^
$data is an empty array that you initialised 2 lines above, so it does not contain any keys or data!
Check, if $data[$products->custom_product_email] is already set in $data array
Try This code
$data = [];
foreach ($saved_data as $products) {
$curVal = isset($data[$products->custom_product_email]) ? $data[$products->custom_product_email] : null;
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}

Recursive method fill array php laravel

I'm trying to create a recursive method to fill an array with each new item found.
function getUserUbigeoString($ubigeo_id){
$ubigeoRepository = new \App\Repositories\UbigeoRepository();
$ubigeos = array();
$ubigeo = $ubigeoRepository->getUbigeo($ubigeo_id);
if(!empty($ubigeo)){
if($ubigeo->ubigeo_id == null){
$ubigeos[] = $ubigeo->name;
}
$ubigeos[] = getUserUbigeoString($ubigeo->ubigeo_id);
}
return $ubigeos;
}
The objective of the code is to get an array fill with all the name of the ubigeos.
0 => ubigeo1
1 => ubigeo2
2 => ubigeo3
etc...
As of right now, i have tried placing the return many different locations, but the closest result i have gotten was:
array:1 [▼
0 => array:1 [▼
0 => array:2 [▼
0 => "Port Dusty"
1 => []
]
]
]
==========EDIT============
Structure of database ubigeos:
id name level ubigeo_id
----------------------------
3 ubigeo1 1 null
37 ubigeo2 2 3
55 ubigeo3 3 37
the output would be a simple array like so, which then i could implode into a comma separated string:
array:1 [
0 => 'ubigeo1'
1 => 'ubigeo2'
2 => 'ubigeo3'
]
so assuming that you really want to call this with function with an Ubigeo instance and only get the names from that and from the parent Ubigeo instances (i.e. calling the function with id 55 initially to get the result array), you can try something like this (I didn't want to modify your function call parameters - normally I would include the array as a function parameter instead of instantiating new one in each recursion step):
function getUserUbigeoString($ubigeo_id)
{
$ubigeoRepository = new \App\Repositories\UbigeoRepository();
$ubigeos = array();
$ubigeo = $ubigeoRepository->getUbigeo($ubigeo_id);
if(!empty($ubigeo))
{
if($ubigeo->ubigeo_id != null) {
$ubigeos = getUserUbigeoString($ubigeo->ubigeo_id);
}
$ubigeos[] = $ubigeo->name;
}
return $ubigeos;
}
Use Can do it with lists method in laravel
Ex :
$ubigeoRepository->lists('ubigeo_id','id')->all();

Array to string conversion with array_walk in PHP

I am tried to add the same string to every array value.
I tried to use array_walk() like I read it on this answer.
But I get: Notice: Array to string conversion
I have also tried to use array_map(), but I get same error notice.
working code
if ($voice->getValue() === Voice::Passive) {
array_walk($aller_form, function(&$value, $key) { $value .= ' être'; });
$aller_form = [
Mood::Indicatif => [
Tense::Futur_compose => [
Person::FirstPersonSingular => 'vais être',
Person::SecondPersonSingular => 'vas être',
Person::ThirdPersonSingular => 'va être',
Person::FirstPersonPlural => 'allons être',
Person::SecondPersonPlural => 'allez être',
Person::ThirdPersonPlural => 'vont être'
]
]
];
}
return $aller_form[$mood->getValue()][$tense->getValue()][$person->getValue()];
not working code
if ($voice->getValue() === Voice::Passive) {
array_walk($aller_form, function(&$value, $key) { $value .= ' être'; });
}
return $aller_form[$mood->getValue()][$tense->getValue()][$person->getValue()];
EDIT:
The complete error log:
Notice: Array to string conversion in on line 2
Warning: Illegal string offset 'futur_compose' on line 4
Warning: Illegal string offset 'firstPersonSingular' on line 4
(I see 6 times this three error lines for every Person once)

Categories