首页 > 解决方案 > 优化 AJAX - Laravel 功能

问题描述

我在一些公式上有点挣扎,这个想法是对所有东西都只有一个公式/函数,所以它很容易维护并且很健壮。

问题是试图结合 AJAX 调用和 laravel 函数。

从一方面来说,我有一个 AJAX 数据表控制器(调用需要采用这种格式):

public function userData(Request $request)
    {
        $event = User::select(
            'users.*',
            DB::raw('IFNULL(b.balance,0) as balance'),
        )
        ->leftJoin(DB::raw('(SELECT seller_id, SUM(total) as balance FROM transactions WHERE concept IN ("TPV") AND status = "ok" GROUP by buyer_id)as b'), 'b.seller_id', '=', 'users.id')
        ->get();
        return $this->formatView($request, $event, 'user'); 
    }

然后,我用于网络其余部分的公式位于模型内的函数中:

public function Balance($seller_id = false){
        return Transaction::emitted()
            ->where('event_id', $this->id)
            ->where('seller_id', $this->seller_id)
            ->whereIn('concept', ['TPV'])
            ->where('status', 'ok')
            ->sum('total'); 
    }

问题是:你知道如何只使用一个公式/函数来处理所有事情吗?

标签: phpajaxlaravel

解决方案


在你的控制器方法中试试这个

在单独的方法中进行常用计算并在此处调用。然后在以下部分更改响应格式

if ($request->expectsJson()){
   //send response to ajax here in json format. note that you should set ajax dataType:'json'
}
//send response for web here.

推荐阅读