【发布时间】:2015-10-14 13:35:06
【问题描述】:
我正在尝试使用旧表的 JSON 输出在 laravel 中播种一个表。
当我尝试在种子文件中使用 file_get_contents('services.json') 时,我得到一个文件不存在的异常,并且我尝试使用 file_exists('services.json') 并返回 false 但是当我从路由文件中尝试它时,它工作得很好,我的餐桌种子。我的路线是这样的:
Route::get('test', function(){
// return JWTAuth::parseToken()->getPayload()->get('username');
Illuminate\Database\Eloquent\Model::unguard();
// \Db::table('service')->truncate();
$servicesDataFromOldDB = file_get_contents('../database/seeds/services.json');
$servicesJson = json_decode($servicesDataFromOldDB);
$services = Illuminate\Support\Collection::make($servicesJson);
$services->each(function($service){
App\Service::create([
'id' => $service->id,
'name' => $service->title,
'description' => $service->desc,
'category' => $service->cat,
'type' => $service->type,
'hours' => $service->hours,
'price' => $service->price,
'note' => $service->note,
'devdays' => $service->devdays
]);
});
Illuminate\Database\Eloquent\Model::reguard();
});
我正在从同一路径获取相同的文件,它能够获取它,但不能在种子文件中获取。我错过了什么?
编辑
dd(file_exists(app_path() . '/database/seeds/services.json'));
即使这是返回false
此外,我在种子文件中做了一个dd(__DIR__),它是正确的路径/var/www/html/archive/database/seeds
【问题讨论】:
-
这样获取它:
file_get_contents(basepath() . '/database/seeds/services.json'); -
PHP 对于相对路径的“当前目录”在哪里可能会很奇怪。您应该尝试使用以下内容构建绝对路径:
realpath(__DIR__ . '../database/seeds/services.json')。__DIR__是当前文件所在目录的路径。 -
@samlev:您的解决方案有效。是的。
realpath的事情奏效了。回答,我会接受。谢谢你。我不知道为什么有人对我的问题投了反对票。这是完全有效的。无论如何,再次感谢。
标签: php json laravel laravel-5 file-get-contents