1
votes

I have the following table structure in my database.

Table Name: tiles

Columns: id, tile_name, tile_thumb, tile_snippet

Table Name: tags

Columns: id, tag_title

Table Name: tile_tags

Columns: id, tile_id, tag_id

Models: Tile, Tag, TileTag

In my main model class for entries I am specifying the following relationship to a model called TileTag which is a pivot table.

<?php namespace Tiles;

use Illuminate\Database\Eloquent\Model;

class Tile extends Model {

    protected $table = 'tiles';


   public function tags() {

        return $this->belongsTo('Tiles\TileTag');

    }
}

During my foreach loop it returns the tile_name and any other columns from my table, except the ones joined by the relatipnship.

@foreach($tiles as $tile)       
        <a href="tile/{{$tile->tile_name}}">
            <li class="col-md-4 mix" data-category="{{ $tile->tags->tag_title }}">
                {!! HTML::image($tile->tile_thumb, null, array('class' => 'img-responsive')) !!}
            </li>
        </a>                
@endforeach 

How can I get my categories/tags linked to my primary entries when they are sorted during each loop?

I try returning the data during the loop by {{ $tile->tags->tag_title }} but it returns an empty string.

Controller Method:

class TileController extends Controller {

/**
 * Display a listing of tiles from the database.
 *
 * @return Response
 */

public function index() {

    // Get tile data from the model
    $tiles = \Tiles\Tile::all();

    return view('pages.index', compact('tiles'));

}

Returned Array: enter image description here

1
Show controller method that takes care of sending data to the view. You may use with() I need to see controller to be sure.Kyslik
@Kyslik Hi! I've added the controller method to my post. Thanks!Miura-shi

1 Answers

2
votes

I think that you don't have to create a model for Tile_Tag. Laravel can handle ManyToMany relationships out of the box (I suppose that this is the type of the relationship because you use pivot table). Your models should be

class Tile extends Model {

protected $table = 'tiles';


 public function tags() {

    return $this->belongsToMany('Tiles\Tag');
 }
}

and

class Tag extends Model {

protected $table = 'tags';


 public function tiles() {

    return $this->belongsToMany('Tiles\Tile');
 }
}

Laravel will know that you have a pivot table named "tag_tile" with columns "tag_id" and "tile_id". Check the relevant documentation here

Then you can iterate through tags collection for each tile like this

@foreach ($tiles as $tile)
         {!!$tile->tile_name!!} 
         @foreach ($tile->tag as $tag)
           {!!$tag->tag_title!!} 
         @endforeach
@endforeach

Hope it helps.