// $result=[];
foreach ($chapter['chapter_content'] as $row) {
$result = CoursePublishChaptercontent::create([
'courseId' => $postdata[$i]['courseId'],
'course_chapter_id' => $postdata[$i]['course_chapter_id'],
'file_id' => $postdata[$i]['file_id'],
'course_chapter_content_id' => $postdata[$i]['course_chapter_content_id'],
]);
}
dd($result->toArray());
dd($result)
shows the below data. I cannot call $result->toArray();
outside the foreach
- it shows the error Undefined variable: result
. When declaring $result
before foreach as $result=[];
, it shows the error Call to a member function toArray() on array
. How can i fix it?Can someone tell me how to achieve this? I also tried declaring $result
as ''
& null
before foreach. Both shows errors Call to a member function toArray() on string
& Call to a member function toArray() on null
respectively.
App\Models\CoursePublishChaptercontent {#441
#table: "course_publish_chapter_contents"
#fillable: array:9 [
0 => "course_chapter_id"
1 => "file_id"
2 => "courseId"
3 => "course_chapter_content_id"
]
#connection: "pgsql"
#primaryKey: "id"
#keyType: "int"
incrementing: true
#with: []
#withCount: []
preventsLazyLoading: false
#perPage: 15
exists: true
wasRecentlyCreated: true
#attributes: array:12 [
"courseId" => 1
"course_chapter_id" => 18
"content_type_id" => 1
"file_id" => null
"course_chapter_content_id" => 17
"id" => 106
]
#original: array:12 [
"courseId" => 1
"course_chapter_id" => 18
"content_type_id" => 1
"course_chapter_content_id" => 17
"content_description" => null
"id" => 106
]
#changes: []
#casts: array:1 [
"deleted_at" => "datetime"
]
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
#forceDeleting: false
#enableLoggingModelsEvents: true
#oldAttributes: []
}
CodePudding user response:
You are on the right track. You can use the collect()
helper to convert the result array into a collection and than you can use the toArray()
method.
This is one way to do it:
$result = [];
foreach ($chapter['chapter_content'] as $row) {
$result[] = CoursePublishChaptercontent::create([
'courseId' => $postdata[$i]['courseId'],
'course_chapter_id' => $postdata[$i]['course_chapter_id'],
'file_id' => $postdata[$i]['file_id'],
'course_chapter_content_id' => $postdata[$i]['course_chapter_content_id'],
]);
}
dd(collect($result)->toArray());