我正在使用Laravel 5.3,ajax制作一个crud应用程序。我在Employee模型上使用了一个访问器,如下所示: -
class Employee extends Model
{
protected $table='employees';
protected $primaryKey = 'id';
protected $fillable= ['name','designation','email','phone','address','bio','user_id'];
public function getAvatarAttribute()
{
if(file_exists(public_path("uploads/employee/employee_{$this->id}.jpg"))){
return url("uploads/employee/employee_{$this->id}.jpg");
}
return url("images/employee_default.jpg");
}
EmployeeController.php: -
public function show(Request $request)
{
if($request->ajax()){
$id = $request->id;
$employee = Employee::find($id);
return response()->json($employee);
}
查看代码: -
<div class="col-sm-3">
<img id="view_avatar" src="" alt="Avatar" class="img-thumbnail">
</div>
<p><b>Employee Name : </b><span id="view_ename" class="text-success"></span></p>
<p><b>Designation : </b><span id="view_designation" class="text-success"></span></p>
<p><b>Mobile No.: </b><span id="view_mobile" class="text-success"></span></p>
<p><b>Email: </b><span id="view_email" class="text-success"></span></p>
<p><b>Address : </b><span id="view_address" class="text-success"></span></p>
使用AJAX获取数据的Jquery代码: -
function fun_view(id)
{
var view_url = $("#hidden_view").val();
$.ajax({
url: view_url,
type:"GET",
data: {"id":id},
success: function(result){
console.log(result);
$("#view_avatar").attr('src',result.avatar);
$("#view_ename").text(result.name);
$("#view_designation").text(result.designation);
$("#view_mobile").text(result.phone);
$("#view_email").text(result.email);
$("#view_address").text(result.address);
}
});
}
这里所有数据都显示使用Ajax除了image。
- 在我的控制器中,当我dd($employee->avatar);
时,它会显示图像的网址。
- 但在console.log(result);
输出中没有关于头像的内容
Console.log(结果)输出: -
address:"dhaka"
bio:"dhaka"
created_at:"2017-03-21 20:00:30"
designation:"partner"
email:"i.mossadek@gmail.com"
id:18
name:"Moloy"
phone:"01555555555"
updated_at:"2017-03-21 20:00:30"
user_id:26
我的问题是我做错了什么?提前谢谢。
答案 0 :(得分:1)
您需要将该属性添加到$appends
。
class Employee extends Model {
...
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['avatar'];
...
}