【问题标题】:file_get_contents doesn't work in seed file but work in the routes file in laravel 5file_get_contents 在种子文件中不起作用,但在 laravel 5 的路由文件中起作用
【发布时间】: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


【解决方案1】:

使用__DIR__可以获得当前文件所在的目录,然后使用realpath()可以获得文件的完整路径。

realpath(__DIR__ . '../database/seeds/services.json');

这意味着您可以设置相对于您正在使用的文件的目录的路径,并确保它可以在代码中的其他任何地方工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 2018-05-11
    • 2015-08-20
    • 2018-07-21
    • 2017-11-16
    • 1970-01-01
    相关资源
    最近更新 更多