SGlavach
SGlavach

Reputation: 25

Obtaining field from table using primary key

Using Laravel and Revisionable Package for tracking changes. In my view I'm populating my table:

@foreach($revisions as $revision)
      @if($revision->key == 'created_at' && !$revision->old_value)
      <tr>
        <td>{{ $revision->revisionable_type }}</td>
        <td>{{ $revision->revisionable_id }}</td>
        <td width="50">{{ $revision->userResponsible()->first_name }}</td>
        <td Width="50"></td>
        <td></td>
        <td>{{ $revision->newValue() }}</td>
        <td width="150">{{ $revision->created_at }}</td>
      </tr>  
      @else
      <tr>
        <td>{{ $revision->revisionable_type }}</td>
        <td>{{ $revision->revisionable_id }}</td>
        <td width="50">{{ $revision->userResponsible()->first_name }}</td>
        <td width="50">{{ $revision->fieldName() }}</td>
        <td>{{ $revision->oldValue() }}</td>
        <td>{{ $revision->newValue() }}</td>
        <td width="150">{{ $revision->updated_at }}</td>
      </tr>  
      @endif 
@endforeach

The second column {{ $revision->revisionable_id }} happens to be the primary key of the user record that was modified. I would like to return the email address or first_name/last_name of that users record. I'm fairly new at this and could use a push in the right direction!

Thanks!

Upvotes: 2

Views: 186

Answers (2)

M.Elwan
M.Elwan

Reputation: 1944

from the variable names revisionable_type & revisionable_id I assume you're using many to many Polymorphic relation. based on that you've to define a relation in the Revision Model with the User like so:

public function users()
    {
        return $this->morphedByMany('App\User', 'taggable');
    }

so you can use all the revisions related to this user $revision->users this will return array and if you're sure that you've only one record related to this object like your case as I think. you can use $revision->users->first()->email or username, etc..

Laravel Docs

Upvotes: 0

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40899

You can access the model that given revision relates to by accessing the revisionable relation of that revision. In your case, in order to display the email property of related model, you could do the following:

<td>{{ $revision->revisionable->email }}</td>

Upvotes: 1

Related Questions