Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel where to place static data

Tags:

php

laravel

I have tried to google out where i can store in Laravel static data ( just simple arrays ) but have not found any obvious reasons or explanations, just some existing solutions.

Data could be for example list of countries. Yes it could be stored in DB but it sounds for me useless since that data would be static and used only for retrieval puposes.

I have seen many approaches for storing data like this for example:

  • Models ( Entities )
  • Storing as package
  • Controllers

Is there any practises where to store such static data? Or maybe "data" it self refers to store data where it should be belong, - database, no matter what operations would be done on it?

like image 262
deividaspetraitis Avatar asked Sep 16 '25 20:09

deividaspetraitis


1 Answers

Laravel is opinionated, and you should be. There is more than one way to do it.

You can make it stay like a config, and query as a piece of config. For example: config/mydata.php (make sure to return an array), and then config()->get('mydata.***').

You can make a helper and register to autoloader, create app/helpers.php,

public function generate_data()
{
    return [ 'x' , 'x' ,'x' ... ];
}

register via composer.json,

{
    "autoload": {
        "files": [
            "app/helpers.php"
        ]
    }
}

Well, if you need another obvious PHP style, create a file anywhere in root project, for example: MY_LARAVEL_PROJECT_ROOT/mydata/country.php, create the file and returning an array of your things. At the end of app/start/global.php, require it,

require base_path().'/mydata/country.php';

It just works like that and have fun :)

like image 141
Pete Houston Avatar answered Sep 18 '25 16:09

Pete Houston