lundi 27 novembre 2017

laravel 5.5 - inject more data into paginate collections

I have 2 tables:

profiles - for user profiles. posts - for user posts.

posts only has a user_id from profiles, to keep the table clean.

my HomeController have a function that get all published posts:

public function index()
    {
        $posts = Post::where('publish','=',1)->orderBy('created_at', 'DSC')->paginate(5);
        return view('home',['posts'=>$posts]);
    }

which post only contains user_id to link it back to its owner. How can I use the user_id from $posts to retrieve user data (user_name, user_image) and append it to its specific post?

I tried:

foreach ($posts->items() as $p) {
 $profile = Profile::where('user_id','=',$p->user_id)->first();
 $p->put('profile',$profile);
}

and I get an error:

Call to undefined method Illuminate\Database\Query\Builder::put()

How can I resolve this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire