我有一个User.php模型.

public function getFullNameAttribute()
{
    if($this->first_name && $this->last_name) {
        return $this->first_name . ' ' . $this->last_name;
    } else {
        return $this->name;
    }
}

在Blade 文件中,如果我们想获得它,我是这样写的.

{{ $user->full_name }}

但我不知道在AJAX中怎么做.我编写了以下代码,结果显示为undefined.

<strong class="f20 mb-1">`+user.full_name+`</strong>

推荐答案

在您的AJAX响应中,您需要确保将full_name属性附加到用户模型.在将模型转换为数组或JSON时,Laravel不会自动附加访问器属性.您可以通过向User模型添加$appends属性来实现此目的:

class User extends Authenticatable
{
    protected $appends = ['full_name'];

    public function getFullNameAttribute()
    {
        if($this->first_name && $this->last_name) {
            return $this->first_name . ' ' . $this->last_name;
        } else {
            return $this->name;
        }
    }
}

在这段代码中,$appends = ['full_name'];告诉Laravel在将用户模型转换为数组或JSON时包含full_name属性.现在,full_name应该在您的AJAX响应中可用.

Laravel相关问答推荐

当未通过验证的字段是值数组时,Laravel$validator->;validator()方法不会引发异常

如何获取多态多对多关系子查询的自动 id 列名?

如何为 CMP 横幅安装谷歌同意脚本?

在 laravel 5 中的表单请求验证后传递旧输入

如何在 Laravel 5.5 的 FormRequest 类中返回自定义响应?

有条件的Eager加载

Laravel 中的合同和 PHP 中的接口有什么区别?

PHP 5.5,什么情况下PHP会导致很高的committed memory

Laravel 5 文件下载:stream() 或 download()

错误:您的要求无法解析为一组可安装的软件包.

如何在 Laravel 中将秒转换为天小时分钟

如何在 Laravel 5.1 中为Electron邮件添加标题

加载模型的所有关系

laravel 搜索多个以空格分隔的单词

如何将对象(模型类型对象)插入到 Laravel 中特定索引号的集合对象中?

在 laravel 的自定义路径中创建模型

Carbon解析到 ISO8601

在我的编辑器中管理上传文件的最佳方式?

Laravel 4 简单路由无法使用 mod_rewrite 和 .htaccess

laravel:如何获取 eloquent 模型的列名?