Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Read file from workbench/vendor package

I am developing a package for laravel4 and I need to read in a csv file. I have been unable to find a way to get the path to the file.

I've tried doing things like:

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

It appears however, that this is relative to the root path of the laravel app and not the package.

I could use app_path() and manually add the workbench/vendor folder on, but that's not ideal. I also don't want the file to "published" to the main app, it needs to remain in the package folder.

In my ServiceProvider it seems I can use $this->guessPackagePath() which gives me the path but this doesn't work for a controller.

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

like image 239
hyarion Avatar asked Jan 30 '26 03:01

hyarion


1 Answers

I found a solution that works, while not exactly what I would have liked, it serves it's purpose.

So this is the folder structure I have:

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

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

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

The dirname is used twice in order to get the parent folder.

By using __FILE__ it keeps the path relative to wherever the script is. This means whether I'm working on it in workbench or whether it's published to the vendor folder or if any parent folders are renamed - the path to the csv file will still work.

like image 121
hyarion Avatar answered Jan 31 '26 20:01

hyarion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!