0

I have hotels and services tables with many to many relationship. I want to get services of specific hotel without using foreach or forelse loop from one line of code.

This is how I tried to do that:

$hotel->services->pluck('name')

Result I get:

["Free Wi-Fi","Free Parking"]

Result is an array of values, I want it to be without brackets and quotes. Any suggestions?

10
  • 4
    If you tack on ->implode(', ') you'll get "Free Wi-FI, Free Parking": laravel.com/docs/8.x/collections#method-implode, is that what you mean? Commented Sep 20, 2021 at 16:08
  • 2
    Tried this and works just fine: $hotel->services->implode('name', ', ') Commented Sep 20, 2021 at 16:31
  • @TimLewis thanks for a hint! Commented Sep 20, 2021 at 16:32
  • No problem! Feel free to add your solution below as a self-answer to properly close this question. Cheers 😄 Commented Sep 20, 2021 at 16:32
  • @lasshak if $hotel->services are not loaded, you should do $hotel->services()->pluck('name')->toArray()->implode(', ') instead. Commented Sep 20, 2021 at 16:48

1 Answer 1

2

Solution:

$hotel->services->implode('name', ', ')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.