2015-10-14 41 views
0

我正嘗試使用舊錶的JSON輸出在laravel中播種表。file_get_contents在種子文件中不起作用,但在laravel的路徑文件中工作5

當我在種子文件試圖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

+0

取其像這樣:'file_get_contents(basepath()。'/database/seeds/services.json');' – Daan

+0

PHP對於'當前目錄'用於相對路徑的位置可能很奇怪。你應該嘗試建立一個像這樣的絕對路徑:'realpath(__DD__。'../database/seeds/service.json')''。 '__DIR__'是*當前文件*目錄的路徑。 – samlev

+0

@samlev:您的解決方案工作。是。 '真正的'事情工作。回答,我會接受它。謝謝。我不知道爲什麼有人投了我的問題。這是完全有效的。無論如何,再次感謝。 – Rohan

回答

1

使用__DIR__你可以得到目錄當前文件在,然後使用realpath(),您可以獲取文件的完整合格路徑。

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

這意味着,你可以設置相對於你工作的文件的目錄的路徑,並確保它會從其他地方的代碼工作。

相關問題