Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: How to get only certain columns from joined tables

I have got 2 joined tables in Eloquent namely themes and users.

theme model:

public function user() {
  return $this->belongs_to('User');
}

user model:

public function themes() {
  return $this->has_many('Theme');
}

My Eloquent api call looks as below:

return Response::eloquent(Theme::with('user')->get());

Which returns all columns from theme (that's fine), and all columns from user (not fine). I only need the 'username' column from the user model, how can I limit the query to that?

like image 258
ralu Avatar asked Feb 06 '13 10:02

ralu


3 Answers

Change your model to specify what columns you want selected:

public function user() {
  return $this->belongs_to('User')->select(array('id', 'username'));
}

And don't forget to include the column you're joining on.

like image 122
user2317976 Avatar answered Nov 14 '22 11:11

user2317976


For Laravel >= 5.2

Use the ->pluck() method

$roles = DB::table('roles')->pluck('title');

If you would like to retrieve an array containing the values of a single column, you may use the pluck method


For Laravel <= 5.1

Use the ->lists() method

$roles = DB::table('roles')->lists('title');

This method will return an array of role titles. You may also specify a custom key column for the returned array:

like image 36
Javi Stolz Avatar answered Nov 14 '22 12:11

Javi Stolz


You can supply an array of fields in the get parameter like so:

return Response::eloquent(Theme::with('user')->get(array('user.username'));

UPDATE (for Laravel 5.2) From the docs, you can do this:

$response = DB::table('themes')
    ->select('themes.*', 'users.username')
    ->join('users', 'users.id', '=', 'themes.user_id')
    ->get();
like image 32
Melvin Avatar answered Nov 14 '22 11:11

Melvin