如何使用 response()->json 将 getAttribute 传递给 Laravel 上的 ajax 结果

joe*_*ion 1 laravel

我有从ajax调用的小laravel函数。然后我必须将结果返回给 ajax 结果。例如

Public function Edit(Request $request){
        $user = User::find($request->id);
       //.........
        return response()->json($user);
}
Run Code Online (Sandbox Code Playgroud)

但是我在“salary”属性上有问题,因为它是从 getSalaryAttribute 方法获取的

public function getPositionnameAttribute(){
   ...........
}
Run Code Online (Sandbox Code Playgroud)

因此,在 ajax 结果返回 'undefined',这是合理的,因为 'salary' 属性不存在。我不需要制作特定的集合来处理薪水参数。

任何建议或指导将不胜感激,谢谢。

Riz*_*lin 5

您有两个选择:

  1. 添加protected $appends = ['salary']到您的模型

或者

  1. 在运行时附加它: $user->append('salary')->toArray();

查看文档:https : //laravel.com/docs/5.8/eloquent-serialization#appending-values-to-json