admin管理员组文章数量:1122846
I have some JSON files, and I want to use them to seed my database in Laravel. Could someone guide me on how to achieve this? Specifically, I want to:
Migrate the database tables required for the JSON data.
Use Laravel's Seeder class to read the JSON files and insert the data into the database.
For context, here is an example of the JSON file (data.json
) I’m working with. It contains an array of user data:
[
{
"name": "John Doe",
"email": "[email protected]",
"age": 30
},
{
"name": "Jane Smith",
"email": "[email protected]",
"age": 25
}
]
I have some JSON files, and I want to use them to seed my database in Laravel. Could someone guide me on how to achieve this? Specifically, I want to:
Migrate the database tables required for the JSON data.
Use Laravel's Seeder class to read the JSON files and insert the data into the database.
For context, here is an example of the JSON file (data.json
) I’m working with. It contains an array of user data:
[
{
"name": "John Doe",
"email": "[email protected]",
"age": 30
},
{
"name": "Jane Smith",
"email": "[email protected]",
"age": 25
}
]
Share
Improve this question
asked Nov 21, 2024 at 11:46
Muhammed SalamaMuhammed Salama
216 bronze badges
2
- in your seeder class you can first read the json data from the file and write your logic to map those data with your database table. Then using eloquent or raw query you can store that data into the table. – sandip bharadva Commented Nov 21, 2024 at 12:00
- What exactly is the problem? Migrating the database, such that the proper columns are created, or reading the data itself? – Nico Haase Commented Nov 21, 2024 at 12:46
1 Answer
Reset to default 1use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class UsersTableSeeder extends Seeder
{
public function run()
{
// Path to your JSON file
$jsonFile = base_path('database/seeders/data.json');
// Read and decode the JSON file
$jsonData = json_decode(File::get($jsonFile), true);
// Insert data into the database
DB::table('users')->insert($jsonData);
}
}
本文标签: phpHow to Seed Data from JSON Files in LaravelStack Overflow
版权声明:本文标题:php - How to Seed Data from JSON Files in Laravel? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736311238a1934665.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论