phplaravellamp

How to use a variable to assign a database to each user in Laravel 5.3 in LAMP?


I have a little application for stock control in a shop which is running in my online homemade server (lamp). I made my web app with Laravel, now I have to use it to control more shops, so my idea is that when a user logs in in the app, they only can access to their own database, so I think I have to pass a variable with the databasename that correspond to every specific shop. how can I do that? is it right to create a virtualhost for each shop(now it could be 6 but can increase in the future)? or should I use one virtualhost and resolve the database assignment programmatically in the webapp? all suggestions are welcome. thanks in advance


Solution

  • I am not a pro with laravel by any stretch however i imagine There is a couple of ways you could do this, That being said you should consider security issues when assigning a database variable / connection based on the users values.

    An example would be to create a database table that holds each shops database name, That way you can make a request to the database and request the database name for that specific shop.

      ID |  Shop_Database_name
    -----+-----
       1 | myshop1
       2 | myshop2
       3 | myshop3
    

    Then you can build your database connection based on the shop_database_name stored in a master table.

    DB::select('shop_database_name')->where('id', $shop->id)->first();
    
    // Now you will build a database connection using something like:
    
    $shopDatabase = DB::connection('shop_database_name')->select(...);
    

    You can also pre-configure your config/database.php with multiple databases for each shop however if you have many shops sign up this would not be the best approach and I would recommend you have an overall table that holds all your database names for each shop.

    If I am on the wrong path feel free to let me know and i will try to help where I can.