nabil nabil - 13 days ago 6
PHP Question

laravel result of 2 objects in one array

I have 2 objects, the first retrieves the comments of the object work and the second retrieves the comments of the object achievement. I want to display the results in a single table containing the list of comments.

$posts1 =\DB::table('posts')
->select('posts.*', 'profils.nom_profil', 'works.titre', 'profils.imagelogo', 'works.description', 'works.like', 'works.nlike')
->join('works', 'posts.work_id','=','works.id')
->join('profils', 'posts.profil_id','=','profils.id')
->where('works.profil_id',$id)
->orderBy('posts.id', 'desc')
->paginate(10);

$posts2 =\DB::table('posts')
->select('posts.*', 'profils.nom_profil', 'achievs.titre', 'profils.imagelogo', 'achievs.description', 'achievs.like', 'achievs.nlike')
->join('achievs', 'posts.achiev_id','=','achievs.id')
->join('profils', 'posts.profil_id','=','profils.id')
->where('achievs.profil_id',$id)
->orderBy('posts.id', 'desc')
->paginate(10);


in view :

@foreach($posts as $post)
.
.
.
@endforeach

Answer

If you are not using Laravel 5.3, using get will return arrays of results as mentioned by @iCode, then you can use the native array_merge.

$posts = array_merge($posts1->get(),$posts2->get());

or add the get() method to your queries and just do

$posts = array_merge($posts1,$posts2);