Home > database >  How to return only a specific data from relationships when using $model->load() in Laravel?
How to return only a specific data from relationships when using $model->load() in Laravel?

Time:02-08

I'm using $user->load(['roles', 'expertises', 'languages']) to return data to a front-end made with Vue.

The Vue component I'm using (Treeselect) needs an array of only ID's to load choices made by user. AFAIK this is not possible ->load(['expertises' => 'myMethod']), this can be useful when you want to return 'expertises' array key, but loading your own filtered data from a custom method.

Please, help me giving some ideas on how to achieve this task.

Thank you.

CodePudding user response:

You actually can eager-load specific columns in a load() method, but the proper syntax would be:

$user->load(['roles:id,user_id', 'expertises:id,user_id', 'languages:id,user_id']);

The problem with that is that you need to include the Foreign Key (I assume user_id in this case) to achieve that, which doesn't fit your requirements of only having the ID.

You're probably better off using ->pluck('id') when passing these to your Components, something like:

$roleIds = $user->roles->pluck('id');
$expertiseIds = $user->expertises->pluck('id');
$languageIds = $user->languages->pluck('id');
// Note: You generally don't need to call `->load()` on a single Model instance; when you try to access them, they will be loaded.

Sidenote, you didn't include your components in your question, so I don't know how you're using them.

That being said, you can load those ->pluck() calls to specific variables, or do it inline for your vue components, whatever works best for your use case.

  •  Tags:  
  • Related