Ad

Relationship For Database Column Type Object

- 1 answer

I have strange column with object records like this: enter image description here

I have troubled with relation with user object (data column)

here is my Temp model:

class Temp extends Model
{
    public function user()
    {
       return $this->belongsTo('App\User');
    }
}

User Model:

class User extends Model
{
    public function temp()
    {
        return $this->hasMany('App\Temp');
    }
}

Controller:

$data['mediaReport'] = Temp::where('type', 'media_report')->paginate(10);

View:

@foreach ($mediaReport as $m)
    <?php $wer = json_decode($m->data); ?>
    <td><span class="bg-primary-700 text-highlight">{{ $wer->id }}</span></td>
    <td align="center">{{ $wer->comment }}</td>
    <td><span><a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="{{ route('profile', $wer->user->username) }}" class="bg-success-700 text-highlight">Reporter</a></span> <span><a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#" class="bg-danger-700 text-highlight">{{-- {{ $m->id }} --}}Delete</a></span></td>
@endforeach

I got error "Trying to get property of non-object", this error in "$wer->user->username" can anybody help me?

Ad

Answer

When you decode the JSON from your data column, the $wer->user value is a string containing user ID, that's why you're getting error when trying to access username property of that string.

In order for it to work, you'd need to fetch the user first, e.g.:

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="{{ route('profile', User::findOrFail($wer->user)->username) }}">

That't the easiest, but not the cleanest solution. The view should just render the data, not decode JSON or load data from the DB - you should do that somewhere in your model creation logic or controller.

Ad
source: stackoverflow.com
Ad