pableiros
pableiros

Reputation: 16032

Lumen read JSON from file

I'm using Lumen Framework and I'm trying to seed my database from a json file. I'm doing something like this:

public function run()
{
    $json = json_decode(file_get_contents('database/seed/file.json'), true);
    ...
}

But when I do the seed command php artisan db:seed, I get this error:

[ErrorException]

file_get_contents(database/seed/file.json): failed to open stream: No such file or directory

I tried to do that: https://stackoverflow.com/a/34201616/3701102 and I got this:

[Symfony\Component\Debug\Exception\FatalThrowableError]

Call to undefined function public_path()

Any ideas what I'm doing wrong?

Thank you

Upvotes: 4

Views: 4843

Answers (1)

Qevo
Qevo

Reputation: 2371

Figure out the script path using __DIR__

public function run()
{
    dd(__DIR__);
}

For this example, lets say the output was /home/vagrant/Code/app/Http/Controllers.

Now this should work (if file permissions are proper)

public function run()
{
    $file_path = realpath(__DIR__ . '/../../database/seed/file.json');
    $json = json_decode(file_get_contents($file_path), true);
    // ...
}

Upvotes: 5

Related Questions