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?

4

2 回答 2

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]);
于 2015-03-31T14:25:24.900 回答
0

Use eager loading

return view('training/single', Training::with('user')->find(1));
于 2015-04-13T09:04:01.150 回答