user0129e021939232
user0129e021939232

Reputation: 6355

laravel retrieve multiple values separated by commas in a column as separate values

Hi I have a column in my database called client_website in my client database and in some cases there are multiple website links, these are separated by commas as so:

www.link1.com, www.link2.com, www.link3.com 

I query the my Projects controller first as I bring

   @foreach ($clients as $client)   
   {{ $client->client_name }}
    {{ $client->email }}
   {{ $client->client_website }}
   @endforeach

It literally is printed out as below:

www.link1.com, www.link2.com, www.link3.com 

and when I wrap it in a <a> tag it fills them the href with all three links, is there anyway I can strip about the commas and spilt them into three separate entities?

Upvotes: 2

Views: 7795

Answers (2)

Razor
Razor

Reputation: 9855

In addition, I recommend you define an accessor in this case:

class Client extends Eloquent {

    public function getClientWebsiteAttribute($value)
    {
        return explode(', ', $value);
    }

}


@foreach ($clients as $client)   
   {{ $client->client_name }}
   {{ $client->email }}
      @foreach ( $client->client_website as $client_website)
          {{ $client_website }}
      @endforeach
@endforeach

Upvotes: 3

barfurth
barfurth

Reputation: 661

You would have to put a second foreach in there which is sort of dirty but it does work. So you would put another foreach and then on the exploded string of websites and that will make an anchor for all websites.

Imagining these are the clients websites:

www.link1.com, www.link2.com, www.link3.com

Your code would be like this:

@foreach ($clients as $client)   
   {{ $client->client_name }}
   {{ $client->email }}
      @foreach (explode(', ', $client->client_website) as $client_website)
          {{ $client_website }}
      @endforeach
@endforeach

This would output:

Client nameClient emailwww.link1.comwww.link2.comwww.link3.com

You can then add all sorts of styling around it. It would work for any number of clients and any number of websites. Just notice that the list of websites needs to be seperated by commas with a trailing space.

Upvotes: 3

Related Questions