LMSouq
php-dev Open

Get Specific Columns Using “With()” Function in Laravel Eloquent

AW
Awais Qarni
1 month ago
3 views
Problem Description
I have two tables, `User` and `Post`. One `User` can have many `posts` and one `post` belongs to only one `user`. In my `User` model I have a `hasMany` relation... <!-- language: lang-php --> public function post(){ return $this->hasmany('post'); } And in my `post` model I have a `belongsTo` relation... public function user(){ return $this->belongsTo('user'); } Now I want to join these two tables using `Eloquent with()` but want specific columns from the second table. I know I can use the Query Builder but I don't want to. When in the `Post` model I write... public function getAllPosts() { return Post::with('user')->get(); } It runs the following queries... select * from `posts` select * from `users` where `users`.`id` in (<1>, <2>) But what I want is... select * from `posts` select id,username from `users` where `users`.`id` in (<1>, <2>) When I use... Post::with('user')->get(array('columns'....)); It only returns the column from the first table. I want specific columns using `with()` from the second table. How can I do that?

AI-Generated Solution

Powered by LMSouq AI · GPT-4.1-mini

✓ Solution Ready
Analyzing problem and generating solution…
Was this solution helpful?
Back to Knowledge Base