DarkFenix
DarkFenix

Reputation: 746

Access a model method by Laravel ajax

I have an ajax call that calls a method from a controller

public function getVisitas(Request $request)
{
    $visitas = Visita::where('usuario','=',$request->id)->get();
    return $visitas;
}

In my model Visita have the following method

public function getDiff()
{
    $fx = $this->fecha; // attribute fecha
    return Carbon::parse($fx)->diffForHumans();
}

From ajax in my view I can access all the attributes of the Visita class, but I do not know how to access the result of the getDiff method

Upvotes: 1

Views: 521

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Rename getDiff to getDiffAttribute and add the diff property to the $appends array:

protected $appends = ['diff'];

Then you'll see a new diff property in returned JSON.

Upvotes: 2

Related Questions