1

I have a dynamic property user in my model:

class Training extends Model
{
    ...

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

And I can easy get username in controller like this:

Training::find(1)->user->name

But I don't know how to perform the same in view. I tried this:

Controller:

return view('training/single', Training::find(1));

View:

{{ $user->name }};

but without success, I'm getting error Undefined variable: user. So it's look like I can't access dynamic property in view.

Any idea how can I use dynamic property in views?

Limon Monte
  • 52,539
  • 45
  • 182
  • 213

2 Answers2

3

I fear that's not really possible. There's no way to set the $this context in your view to the model. You could convert the model into an array with toArray() but that would include the related model and you would have to access it with $user['name'].

I personally would just declare the user variable explicitly:

$training = Training::find(1);
return view('training/single', ['training' => $training, 'user' => $training->user]);
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • Unfortunately, I wasn't clear in my question. You can pass array of key value or object to view. So I passing object ``Training`` which has dynamic property ``user``. For example with code from question I can access ``user_id`` property, but can't access dynamic one ``user``. – Limon Monte Mar 31 '15 at 14:31
  • 1
    Hmm. I fear that's not really possible. You could convert the model into an array but that would include the related model. Can't you just do `$training->user->name` in your view or pass user explicitly `['user' => Training::find(1)->user]`? – lukasgeiter Mar 31 '15 at 14:38
  • Yes, it seems impossible to use dynamic property in view. This code ``['training' => Training::find(1), 'user' => Training::find(1)->user]`` works as expected. – Limon Monte Mar 31 '15 at 14:44
  • can you please edit your answer so I can accept it for further readers? – Limon Monte Mar 31 '15 at 14:46
  • 2
    Answer edited. Also note that calling `find(1)` twice will run the same db query twice. Instead store it in a variable like in my answer ;) – lukasgeiter Mar 31 '15 at 14:50
0

Use eager loading

return view('training/single', Training::with('user')->find(1));