Trên laravel bạn muốn import dữ liệu từ 1 file Json có sẵn, sử dụng seeder của laravel, đây là một Tip hay dành cho bạn. Ở đây tôi muốn seed dữ liệu users.
- Giả sử tôi có 1 file users.json, tôi đặt file này trong thư mục database của laravel. File json của tôi có dạng:[
{
"id": "1",
"email": "admin@admin.com",
"first_name": "Minh",
"last_name": "Nguyen",
"password": "$2y$10$5dIuEeS1C4oKij41rYFBU.SXtaztO2XqHHvT/U3Mi9wB86znOcqY2"
},
{
"id": "2",
"email": "aaaa@minhcat.info",
"first_name": "Lan",
"last_name": "Ngoc",
"password": "$2y$10$5dIuEeS1C4oKij41rYFBU.SXtaztO2XqHHvT/U3Mi9wB86znOcqY2"
},
{
"id": "3",
"email": "bbbb@minhcat.info",
"first_name": "Van",
"last_name": "Test",
"password": "$2y$10$5dIuEeS1C4oKij41rYFBU.SXtaztO2XqHHvT/U3Mi9wB86znOcqY2"
}
]
- Tiếp theo tôi tạo file seeder trong thư mục /database/seeds
UserTableSeeder.php
delete();
$json = File::get("database/users.json");
$data = json_decode($json);
foreach ($data as $obj) {
User::create(array(
'id' => $obj->id,
'email' => $obj->email,
'first_name' => $obj->first_name,
'last_name' => $obj->last_name,
'password' => $obj->password
));
}
}
}
?>
- File migration để tạo tables users:
increments('id');
$table->string('email')->unique();
$table->string('first_name');
$table->string('last_name');
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
- Bây giờ bạn chỉ việc chạy lệnh: "php artisan db:seed" là dữ liệu sẽ được đưa vào database từ file json của bạn.

0 Nhận xét:
Đăng nhận xét
Rất mong các ý kiến của các bạn khi đọc bài viết này !