Laravel 5 - using dynamic properties in view

泄露秘密 提交于 2019-12-08 08:17:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!