问题
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?
回答1:
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]);
回答2:
Use eager loading
return view('training/single', Training::with('user')->find(1));
来源:https://stackoverflow.com/questions/29370800/laravel-5-using-dynamic-properties-in-view