Laravel - reading file from package workbench / vendor

I am developing a package for laravel4 and I need to read in a CSV file. I haven't been able to find a way to get the file path.

I've tried doing things like:

$file = File::get('data/myfile.csv');

However, it looks like it refers to the root path of the laravel app, not the package.

I could use app_path()

and manually add the workbench / vendor folder, but that's not ideal. I also don't want the file to be "published" in the main application, it must remain in the package folder.

In my ServiceProvider, it seems like I can use $this->guessPackagePath()

that which gives me the path, but that doesn't work for the controller.

How can I get the package path to read in this file?

+3


source to share


2 answers


I found a solution that works, although not exactly what I would like, it serves a purpose.

So, I have a folder structure:

workbench
    - vendorname
      - appname
        - src
            - controllers
                - mycontroller.php
            - data
                - myfile.csv

      

In mycontroller.php I can access the csv file like below:



$path = dirname(dirname(__FILE__)) . '/data/';
$contents = File::get($path . 'myfile.csv');

      

dirname

is used twice to get the parent folder.

By using __FILE__

, it stores the path relative to where the script is located. This means I am working on it in workbench or whether it is published in the vendor folder or if any parent folders are renamed - the csv file path will still work.

+1


source


Here is the routine I ran into in the Testbench TestCase class:



protected function getPackagePath()
{
    return realpath( implode( DIRECTORY_SEPARATOR, [
        __DIR__,
        '..',
        'src',
        'MyPackage'
    ] ) );
}

      

0


source







All Articles