从刀片中的关系访问数据? - Laravel

I have this code snippet in my blade:

 @foreach($products as $product)
     <tr>
         <td></td>
         <td>{{ $product->name  }}</td>
         <td>{{$product->tags}}</td>
         <td>{{$product->created_at}}</td>
         <td>
             // some other code and buttons
         </td>
     </tr>
 @endforeach

In $product->tags ( tags is the name of my relation ) are the tags I need and some other things, but I only want the tags.

I tried to reach them with $product->tags->tag but this hasn't worked for me. Can anybody tell me how I can access only the tags?

If you have a relationship set between your Products and it's Tags (https://laravel.com/docs/5.1/eloquent-relationships)

Products Model

//namespace and use statements
class Products extends Model
{
    /**
     * Get all of the tags for the product.
     */
    public function tags()
    {
        return $this->hasMany('App\Tags');
    }
}

Tags Model (assuming tags can be used for multiple products)

//namespace and use statements
class Tags extends Model
{
    /**
      * The tags that belong to the product.
      */
    public function products()
    {
        return $this->belongsToMany('App\Products');
    }
}

Then you can query in you controller for the products with their tags (https://laravel.com/docs/5.1/eloquent-relationships#querying-relations)

$products = App\Products::with('tags')->get();

Then you can simply access them in your view with your current code but using

@foreach($products as $product)
    <tr>
        <td></td>
        <td>{{ $product->name }}</td>
        @foreach($product->tags as $tag)
            <td>{{ $tag->name }}</td>
        @endforeach
        <td>{{ $product->created_at }}</td>
        <td>
            // some other code and buttons
        </td>
     </tr>
 @endforeach

Try this:

@foreach($product->tags as $tag)
   <td>{{ $tag->tag }}</td>
@endforeach

$product->tags returns an array of Tag objects.