Reputation: 433
To explain this better here is my Code:
$mydate=Carbon::now()->addHours(8);
$newdate=$mydate->toDateString();
$myquery = DB::table('attendances')->where('date_only', '=', $newdate)->orderBy('logon','asc')->get();
$counter=0;
foreach ($myquery as $newquery)
{
$query1[$counter]=$newquery->user_id;
$finalquery[$counter]= DB::table('employees')->where('id', '=', $query1[$counter])->get();
$counter++;
}
var_dump($finalquery[2]);
The output of this code will be this:
array(1) { [0]=> object(stdClass)#160 (6) { ["id"]=> int(23) ["firstname"]=> string(3) "Kim" ["lastname"]=> string(7) "Samsung" ["position"]=> string(10) "Programmer" ["created_at"]=> string(19) "2014-11-25 07:21:31" ["updated_at"]=> string(19) "2014-11-25 07:21:31" } }
What i want to do is to access one of its value so I tried this
//I change
var_dump($finalquery[2]);
//to this
var_dump($finalquery[2]->firstname);
But what I get is just error. Error Code 500
Upvotes: 1
Views: 355
Reputation: 1875
try this
// not necessary
foreach ($myquery as $key => $newquery)
{
$query1[$key]=$newquery->user_id;
$finalquery[$key]= DB::table('employees')->where('id', '=', $query1[$key])->get();
}
// necessary
print_r($finalquery->toArray()); // if its array of objects I'm converting it into an array
// or
print_r($finalquery);
Edit: buddy my suggestion is to use joins
This single query will get you all the data need not use a foreach
with several queries Reference
$myquery = DB::table('attendances')->select('employees.id as emp_id','attendances.id as att_id',/*your fields*/)
->leftJoin('employees', 'employees.id','=','attendances.id')
->where('date_only', '=', $newdate)
->orderBy('attendances.logon','asc')->get();
print_r($myquery->toArray());
in controller
return View::make('home', array('mydata' => $finalquery));
in view: (for blade)
@if($mydata && count($mydata) > 0)
@foreach($mydata as $data)
{{ $data->id }}<br>
{{ $data->name }}<br>
{{ $data->etc }}<br>
@endforeach
@else
<p>sorry no data to display</p>
@endif
Upvotes: 1
Reputation: 46900
Your var_dump
suggests finalquery[2]
is an array of objects, not an object itself. So this wont work
var_dump($finalquery[2]->firstname);
This will
var_dump($finalquery[2][0]->firstname);
Like
foreach($finalquery[2] as $obj)
{
echo $obj->firstname;
}
Upvotes: 0