Reputation: 6612
I want to paginate a Union query result. I wrote this :
use Illuminate\Support\Facades\Input;
use Illuminate\Pagination\Paginator;
$page = Input::get('page', 1);
$paginate = 10;
$members = DB::table("members")
->select("id", "first_name", "last_name", "email", "created_at")
->where("site_id", $id);
$users = DB::table("users")
->select("id", "first_name", "last_name", "email", "created_at")
->where("site_id", $id)
->union($members)
->get()->toArray()
$slice = array_slice($users, $paginate * ($page - 1), $paginate);
$data = new Paginator($slice, $paginate);
return View::make('main.pages.search',compact('data','searchTerm'));
Now I want to access result in the search
blade template.Suppose I wrote this :
<div class="container">
@foreach ($data as $user)
{{ $user->first_name }}
@endforeach
</div>
{{ $data->links() }}
But I got this error :
Trying to get property of non-object (View: D:\wamp\www\aids\resources\views\main\pages\search.blade.php
That can not recognize $user
and it's name
property
What is Problem ?
Update:
while return $data
from above coeds return this :
{
"per_page": 2,
"current_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 6,
"first_name": "ali",
"last_name": "hassani",
"created_at": "2012-04-16 22:11:46",
"email": "[email protected]",
},
{
"id": 7,
"first_name": "hossein",
"last_name": "rezaei",
"created_at": "2012-04-16 22:11:46",
"email": "[email protected]",
},
]
}
I tried $data->data
to access result but same error occures.
Update 2:
I found that when I added {{dd($user)}}
like this :
<div class="container">
@foreach ($data as $user)
{{dd($user)}}
{{ $user->first_name }}
@endforeach
</div>
that returns an array
contain Result instead object
.
Upvotes: 0
Views: 344
Reputation: 6612
According to @iCode guidance I found that I should use slice instead array_slice
method. in fact that part of code that used array_slice
changed to :
$slice = $workshops->slice($paginate * ($page - 1), $paginate);
Upvotes: 0
Reputation: 17668
In your controller, you are calling function toArray
on the query result which converts the collection into a plain PHP array
. If the collection's values are Eloquent models, the models will also be converted to arrays.
So your foreach
in view should be as:
<div class="container">
@foreach ($data['data'] as $user)
{{ $user['first_name'] }}
@endforeach
</div>
Upvotes: 1