Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load just ids of relation (pluck)

I have a simple app, using Laravel 5.5.13.

public function index()
{
    return Pet::all();
}

This lists all pets. I have many to many relation where many users can own a the same pet (the pet's human family).

I want to load those users.

Doing return Pet::with('users')->get(); does the trick, however it loads all kind of excessive infromation, like the users api_token etc, I just want to pick some fields, like id and name:

I was hoping to just get users: [1, 12] for the example in the screenshot above.

I tried pluck like this return Pet::with('users')->get()->pluck('id') but this gives me only the ids.

like image 282
Blagoh Avatar asked Dec 14 '25 17:12

Blagoh


1 Answers

You can select specific fields like this:

Pet::with(['users' => function($query) { $query->select('id', 'name'); }])->get()
like image 121
Leonardo Barbosa Avatar answered Dec 16 '25 23:12

Leonardo Barbosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!