https://jsonplaceholder.typicode.com/posts是json数据链接。我想获取、获取并将这些数据保存在数据库中。我收到的所有帮助都是关于使用foreach方法在Blade模板中获取和显示数据。我没有找到任何关于保存这些数据的解决方案(我指的是一次数据库中的全部100个数据)。我只能保存一个数据,因为我从那个API链接中获得的数据是二维的(我指的是其他索引数组中的数组)。下面给出了控制器代码,用于只保存一个数据,而不是将整个数据保存为一个对象或数组。
<?php
namespace App\Http\Controllers;
use App\Models\apipost;
use Illuminate\Support\Facades\Http;
class postController extends Controller
{
public function index(){
$response=json_decode(Http::get('https://jsonplaceholder.typicode.com/posts'));
$apipost=new apipost();
$apipost->userId=$response[0]->userId;
$apipost->id=$response[0]->id;
$apipost->title=$response[0]->title;
$apipost->body=$response[0]->body;
$apipost->save();
return redirect()->to('/');
}
}发布于 2022-03-31 20:56:31
我猜您的表具有与响应相同的列,因此您可以尝试如下:
public function index()
{
$response = Http::get('https://jsonplaceholder.typicode.com/posts')->json();
foreach ($response as $post) {
apipost::create($post);
}
return redirect()->to('/')
}->json()将在数组中转换您的响应。您可以在这里看到文档:https://laravel.com/docs/9.x/http-client#making-requests
https://stackoverflow.com/questions/71698515
复制相似问题