简体   繁体   中英

Laravel many to many grab only one value from relation

I have a many to many relation between Expense and Tag . Now I want to grab only the name from all tags that are related to an Expense .

So, let's say I have an Expense :

$expense = Expense::first();

And now I can grab all tags easily:

$tags = $expense->tags;

This will give me a collection of Tags. Ideally, I want to have an array of the tag names:

array:5 [▼
  0 => "tag1"
  1 => " tag2"
  2 => " tag3"
  3 => " tag4"
  4 => " tag5"
]

Now I can accomplish that by doing this:

$tags = $expense->tags;

$new_tags = [];

foreach($tags as $tag)
{
    $new_tags[] = $tag->name;
}

But is there a cleaner way, especially without having to use foreach ? I tried something like this:

$tags = $expense->tags->value('name')->toArray();

$tags = $expense->tags()->value('name')->toArray();

But both aren't working. Is there a way to get this working?

Try this

$tags = $expense->tags->pluck('name')->toArray();

or

$tags = $expense->tags->pluck('name')->all();

Is that what you're looking for?

$tags = $expense->tags->pluck('name');

You can further read over here: https://laravel.com/docs/5.6/collections#method-pluck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM