gpt4 book ai didi

php - Laravel 存储函数更改返回数据

转载 作者:行者123 更新时间:2023-12-05 07:58:41 27 4
gpt4 key购买 nike

很确定我在这里做错了什么,只是不知道是什么或在哪里。

我有一个 Laravel Controller ,它处理 ajax post 请求并将 curl 请求的结果返回给该 ajax 调用:

public function store()
{
/** Receive long and lat through ajax **/
$long = Input::get('longitude');
$lat = Input::get('latitude');
$location = $lat . "," . $long;
$url = blablable;
$curl = curl_init();
curl_setopt_array($curl,
array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$result = curl_exec($curl);
return $result;
curl_close($curl);
}

这有效:curl 返回一个 JSON 数组,该数组被传递回 ajax 调用。

但是现在我想将传入的数据保存到数据库中:

$location = new Location();
$location->latitude = Input::get('latitude');
$location->longitude = Input::get('longitude');
$location->save();

我在函数的顶部添加了这 4 行,数据被保存到数据库,但 JSON 数组被抓取,不知何故 <!-- app/models/Location.php -->被添加到返回的顶部,使 JSON 数组无效。

不知道是什么原因造成的,所以非常感谢任何提示或建议!

-- 编辑 1 --

Input::all(); 的结果是

array(2) {
["latitude"]=>
string(10) "50.8809794"
["longitude"]=>
string(9) "4.6920714"
}

最佳答案

这不是一个解决方案,而是一种清理代码的方法:

  1. 您不需要使用 curl,而是可以使用 Request::create()Route::dispatch()
  2. 您应该在模型中使用 protected $fillable 属性来清理新条目。

您的代码可以变成:

public function store()
{
// This is for saving the entry
$location = new Location();
$location->fill(Input::all());
$location->save();

// This is for the cURL
// (assuming this is a GET requst, but other methods are available)
$request = Request::create('/path/to/url/', 'GET');

$response = Route::dispatch($request);

// Do stuff with the $response or just return it
return $response;
}

关于php - Laravel 存储函数更改返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23916490/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com