Laravel 5 - 使用动态属性视图 [英] Laravel 5 - using dynamic properties in view

查看:129
本文介绍了Laravel 5 - 使用动态属性视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态资源 用户在我的模型中:

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:

控制器:

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

查看:

{{ $user->name }};

但没有成功,我收到错误未定义的变量:user 。所以看起来像我无法访问动态属性。

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?

推荐答案

我担心这不是真的可能。没有办法在视图中将 $ this 上下文设置为模型。您可以将模型转换为 toArray()的数组,但这将包括相关模型,您必须使用 $ user ['名字']

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]);

这篇关于Laravel 5 - 使用动态属性视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆