SETUP
Model
public function totalValidated()
{
return $this->hasOne('user')->where('validated', '=', "1")
->selectRaw('district_id, count(*) as total')->groupBy('district_id');
}
Controller
$districts = District::select(array('id', 'name'))
->with(array('usersCount','totalValidated'))
->get();
return View::make('districts.index', compact('districts'));
I have the following data returned:
0: {
id: 1,
name: "Northern California",
total_validated: {
district_id: "1",
total: 3
}
},
1: {
id: 2,
name: "Southern California",
total_validated: {
district_id: "2",
total: 30
}
}
View
#foreach ($districts as $district)
<tr>
<td>{{$district->name}}</td><td>{{$district->total_validated->total}}<td>
<tr>
#endforeach
Question
How do i display the "total" in "total_validated" per district? The above only gets me a
"Trying to get property of non-object"
which i know is wrong, but i'm not sure how to get the value out of that nested array.
Thanks!
Not sure what's up with blade, but plain php worked
<?php echo($district['totalValidated']['total']) ?>
Related
I have a table with multiple rows, which contain parent and child rows, in case I need to get data to the same collection. This means getting child row data inside the parent row using laravel.
id
type
price
is_substitute
subsitute_parent
1
Type A
12
0
null
2
Type B
44
1
1
3
Type C
23
1
1
4
Type D
11
0
null
5
Type E
45
1
4
6
Type F
25
1
4
"subsitute_parent" id means the parent row id of this table. How can I do this using laravel.
I tried using get all data from the table and the add collection to foreach and then create parent row array and child row array, but this method is not efficient.
$returnedData = ItemModel::all();
$structPODetails = [];
foreach ($returnedData as $tableRow) {
if (!empty($tableRow->subsitute_parent)) {
$structPODetails['child_items'][] = $tableRow;
} else {
$structPODetails['parent_items'][] = $tableRow;
}
}
return $structPODetails;
As I understood
In ItemModel.php
class ItemModel extends Model
{
public function parent()
{
return $this->belongsTo(ItemModel::class, 'subsitute_parent');
}
public function children()
{
return $this->hasMany(ItemModel::class, 'subsitute_parent');
}
}
Then in the controller, add.
$structPODetails = ItemModel::with('children')->get();
This will give you output as
[
{
"id": 1,
...
"children": [
{
"id": 2,
..
},
{
"id": 3,
...
}
]
},
{
"id": 4,
...
"children": [
{
"id": 5,
...
},
{
"id": 6,
..
}
]
}
]
use laravel Eloquent way.
In the model add relationship has many
public function substitutes()
{
return $this->hasMany(ItemModel::class, 'subsitute_parent');
}
and in your controller
$substitutes = ItemModel::with([
'substitutes' =>
function ($query) {
$query->whereNotNull('subsitute_parent');
}
])->whereHas(
'substitutes',
function ($query) {
$query->whereNotNull('subsitute_parent');
}
)->get();
Model Logic
public function substitutes()
{
return $this->hasMany(self::class, 'subsitute_parent');
}
controller logic
$substitutes = ItemModel::with(['substitutes'])->whereHas('substitutes', function ($query) {
$query->whereNotNull('subsitute_parent');
})->get();
I have problem with eloquent query. I am using eager loading (one-to-many Polymorphic Relationship) to sortby 'historyable.date', JSON below.
[
{
"product_id":12,
"product_name": "Product C",
"historyable_type":"App\\Delivery",
"historyable":{
"id":2,
"date":"0303\/0404\/2020",
"for":"Customer A",
"created_at":"2020-04-02T09:46:48.000000Z",
}
},
{
"product_id":1,
"product_name": "Product A",
"historyable_type":"App\\Transfer",
"historyable":{
"id":1,
"date":"0202\/0404\/2020",
"for":"First Balance ****",
"created_at":"2020-04-02T07:30:45.000000Z",
}
},
{
"product_id":11,
"product_name": "Product B",
"historyable_type":"App\\Delivery",
"historyable":{
"id":2,
"date":"0303\/0404\/2020",
"for":"Customer B",
"created_at":"2020-04-02T09:46:48.000000Z",
}
}
]
And i try to get result like this
[
{
"product_id":1,
"product_name": "Product A",
},
{
"product_id":12,
"product_name": "Product C",
},
{
"product_id":11,
"product_name": "Product B",
}
]
Is it possible to run with Nested Lazy Eager Loading Laravel?
Product Model
public function track() {
return $this->hasMany('App\History');
}
History Model
public function historyable(){
return $this->morphTo()->orderBy('date', 'desc');
}
Product Controller
public function json_history(Product $product) {
$data = $product->with('track.historyable')
->where('id', $product->id)
->first();
return $data->track;
}
I Have database like this
Products Table
#id
#name
Histories Table
#product_id
#product_name
#historyable_id
#historyable_type
Deliveries Table
#id
#date
#for
Transfers Table
#id
#date
#for
public function json_history(Product $product) {
$data = Product::with('track.historyable')
->where('id', $product->id)
->first();
$arr = $data->track->toArray();
$date = array();
$create = array();
foreach ($arr as $key => $row)
{
$date[$key] = $row['historyable']['date'];
$create[$key] = $row['historyable']['created_at'];
}
array_multisort($date, SORT_DESC, $arr);
array_multisort($create, SORT_DESC, $arr);
return $arr;
}
I don't know but it works for me.. but i still find the shorter way for this..
In controller get data from db like this, I want to pass whole of $request to another function in this controller to get price it calculating price based of many things from $request:
$user = Auth::user();
$query = Post::query();
$query
->where('province', '=', $user->province)
->where('city', '=', $user->city);
$customers = $query->get();
$customers['calculator'] = $this->calculator($request); // call function
my problem is it return like this:
{
"0": {
"id": 1,
"hash": "RqH29tkfm1dwGrXp4ZCV",
},
"1": {
"id": 3,
"hash": "RqH29tkfm1dwGsXp4ZCV",
},
"calculator": {
"price": 1
}
}
But I need to use that function for each data, and result should be like this:
{
"0": {
"id": 1,
"hash": "RqH29tkfm1dwGrXp4ZCV",
"calculator": {
"price": 1
}
},
"1": {
"id": 3,
"hash": "RqH29tkfm1dwGsXp4ZCV",
"calculator": {
"price": 1
}
}
}
What you want is to set a calculator key for each item in the $customers collection. So you need to loop over it:
foreach ($customers as $customer) {
$customer->calculator = $this->calculator($request);
}
Notice that since the $customer is a Model you should set the calculator as a property. Internally it will be set to the attributes array.
I am new to Laravel and I am trying to display data from the controller to view. I am able to display data from the first level of #foreach( $item->name, $item->address, etc) with ease. But I am having difficulty accessing a child of "subscriber_subscription" via Laravel blade convention. I tried accessing it using via code below:
#foreach ($items as $item)
...
#foreach($item->subscriber_subscription as $subs)
...
...
#endforeach
...
...
#endforeach
JSON data used is:
[
{
"id":1,
"name":"Jollibee",
"address":"31st cor. 9th Strata bldg. Ortigas Ave. Pasig City, 600",
"contact":"87000",
"email":"admin#jollibee.com.ph",
"created_at":"2017-09-17 01:04:11",
"updated_at":"2017-09-17 01:04:12",
"subscriber_code":"jollibee",
"subscriber_subscription":[
{
"id":1,
"subscriber_id":1,
"subscription_id":1,
"start_date":"2017-09-17 01:35:27",
"end_date":"2018-09-17 01:35:27",
"created_at":"2017-09-17 01:35:23",
"updated_at":"2017-09-17 01:35:23"
},
{
"id":6,
"subscriber_id":1,
"subscription_id":1,
"start_date":"2017-10-17 01:35:27",
"end_date":"2018-10-17 01:35:27",
"created_at":"2017-09-17 01:35:23",
"updated_at":"2017-09-17 01:35:23"
}
]
},
{
"id":2,
"name":"Bench",
"address":"2207 Tektite Bldg. Ortigas Ave. Pasig City, 1600",
"contact":"+639171234567",
"email":"admin#benchtm.com.ph",
"created_at":"2017-09-17 01:47:10",
"updated_at":"2017-09-17 01:47:11",
"subscriber_code":"bench",
"subscriber_subscription":[
{
"id":4,
"subscriber_id":2,
"subscription_id":1,
"start_date":"2017-09-17 14:19:15",
"end_date":"2018-09-17 14:19:16",
"created_at":"2017-09-17 14:19:20",
"updated_at":"2017-09-17 14:19:20"
},
{
"id":5,
"subscriber_id":2,
"subscription_id":2,
"start_date":"2017-09-17 14:19:15",
"end_date":"2018-09-17 14:19:16",
"created_at":"2017-09-17 14:19:20",
"updated_at":"2017-09-17 14:19:20"
}
]
}
]
I'm getting this error: Invalid argument supplied for foreach()
Any help will be appreciated. Peace :-)
Thanks
I've solved it. Apparently, i have to use $item->SubscriberSubscription which is the name of my model
I Have 2 table that I want to join them and fetch some data like this
I have one student with multiple grade
{
"student": {
"studentID": "2",
"Name": "s1",
"age": " 12",
"grade": [
{
"GradeID": "2"
},{
"GradeID": "3"
}
]
}
I fetch this data from two query in a function in my model and then use json_encode in my controller for my output
but I have this
{
"student": {
"studentID": "2",
"Name": "s1",
"age": " 12"
},
"grade": [
{
"GradeID": "2"
},{
"GradeID": "3"
}
]
}
and now I don't know how to use json_encode for the first format.
thanks
my model(student):
function get_student_id($id)
{
$student['student']=
$this->db->select('tbl_student.*')
->from('tbl_student')
->where('tbl_student.SID',$id)
->get()->row();
$student['grade']=
$this->db->select('tbl_grade.GradeID')
->from('tbl_grade')
->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
->where('tbl_student.SID',$id)
->get()->result();
return $student;
}
my controller:
public function get_student_id()
{
$id = $input['one'];
$this->load->model('student');
$temp=$this->student->get_student_id($id);
$output= json_encode($temp);
die($output);
}
You just have to structure the array you're returning from the model correctly. You're putting everything inside two subarrays called student and grade, which are inside the outer array student. Try this:
my model(student):
function get_student_id($id)
{
$student=
$this->db->select('tbl_student.*')
->from('tbl_student')
->where('tbl_student.SID',$id)
->get()->row();
$student['grade']=
$this->db->select('tbl_grade.GradeID')
->from('tbl_grade')
->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
->where('tbl_student.SID',$id)
->get()->result();
return $student;
}
I'm not totally certain you want to call get->row() on the first query, if that doesn't work try get->row_array()