WellNo WellNo - 6 months ago 22
PHP Question

Accessing data from a realation in blade? - 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 realation ) 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 haven't worked for me. Does anybody can tell me how I can access only the tags?

Answer

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