user3557451
user3557451

Reputation: 134

Laravel Access to several tables

I'm having an issue in accessing to data that are related in more than one table, here my code:

<table class="table table-striped">
    <thead>
        <th>Ejercicio</th>
        <th>Unidad</th>
        <th>Descripcion</th>
        <th>Tipo actividad</th>
        <th>Operaciones</th>
    </thead>
    @foreach($exercises as $exercise)
    <tbody>
        <td>{{$exercise->name}}</td>
        <td>{{$exercise->unit}}</td>
        <td>{{$exercise->description}}</td>
        <td>{{$exercise->activity_id}}</td>
        <td>
            <?php echo link_to('exercise/edit/'.$exercise->id, $title = 'Editar', $attributes = array('class' => 'btn btn-primary'), $secure = null); ?>                
        </td>
    </tbody>
    @endforeach
</table

on line <td>{{$exercise->activity_id}}</td> this is just a foreign key for another table named activity_type which has an id and a name, so what I wanted to be shown is the name with this id.

How can I do that?

Upvotes: 0

Views: 40

Answers (2)

Mina Abadir
Mina Abadir

Reputation: 2981

You need to build relations in your models.

In your Exercise.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Exercise extends Model
{
    public function activity_type()
    {
      return $this->belongsTo('App\ActivityType','activity_type');
    }
}

And in your ActivityType.php, this is not really needed in your case, but if you want to get the inverse relationship.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ActivityType extends Model
{
    public function exercises()
    {
      return $this->hasMany('App\Exercise');
    }
}

After that you can access the Activity properties this way:

<td>{{$exercise->activity_type->name}}</td>

Upvotes: 0

Imtiaz Pabel
Imtiaz Pabel

Reputation: 5443

First write a relation on your base model.Here i give you an example belongs to relation

public function ActivityRelation()
{
    return $this->belongsTo('App\ActivityType', 'id', 'activity_id');
}

Then you can use like that

{{$exercise->ActivityRelation->name}}

Upvotes: 1

Related Questions