Hardist
Hardist

Reputation: 1983

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?

Upvotes: 3

Views: 42

Answers (2)

MyLibary
MyLibary

Reputation: 1771

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

Upvotes: 3

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

Try this

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

or

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

Upvotes: 5

Related Questions