通过Laravel Ajax访问模型方法 [英] Access a model method by Laravel ajax

查看:47
本文介绍了通过Laravel Ajax访问模型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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;
}

在我的模型Visita中,具有以下方法

In my model Visita have the following method

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

在我看来,从ajax可以访问Visita类的所有属性,但是我不知道如何访问getDiff方法的结果

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

推荐答案

getDiff重命名为getDiffAttribute

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

protected $appends = ['diff'];

然后,您将在返回的JSON中看到一个新的diff属性.

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

这篇关于通过Laravel Ajax访问模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆