1

I am making a crud application using Laravel 5.3, ajax. I am using a an accessor on my Employee model as following:-

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

view code:-

<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>

Jquery Code for get data using AJAX:-

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

Here all the data show using Ajax except image. - In my controller when I dd($employee->avatar); it shows the url of image. - but in console.log(result);output there is nothing about avatar

Console.log(result) output:-

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

My question is where I am doing wrong? Thanks in advance.

Mrsk
  • 129
  • 5
  • 13

1 Answers1

1

You need to add the attribute to $appends.

class Employee extends Model {
    ...    
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['avatar'];
    ...
}
Saumini Navaratnam
  • 8,439
  • 3
  • 42
  • 70