PHP - Access data for .env laravel - php

I am starting the program with Laravel and I have in my ".env" file my access data to the server:
USER_SERVER=user
PASSWORD_SERVER=123456789
I have my role in my controller:
public function connectServer()
{
$connection=ssh2_connect(172.17.2.33, 22);
ssh2_auth_password($connection, USER_SERVER, PASSWORD_SERVER);
$stream=ssh2_exec($connection, "df -h");
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
}
My role above has problems. What is the correct way to call the user and password of my ".env" file for my function?

You should use the configuration system for these values. You can add to a current configuration file in the config folder or create your own that returns an associative array. We will use the env() helper to pull the values you set in the .env file:
<?php
return [
...
'server' => [
'user' => env('USER_SERVER', 'some default value if you would like'),
'password' => env('PASSWORD_SERVER', ...),
],
...
];
If you added this key to the services.php file in the config folder you would then access this configuration value via the Config facade or the config() helper function:
// if we want a value from the services.php file
Config::get('services.server.user');
config('services.server.user');
// if you want all of them for that server array
$config = config('services.server');
echo $config['user'];
Using the configuration system this way allows you to use the "config caching" that Laravel provides, as you will not have any env() calls in your application, except for in the config files, which can be cached. [When configuration caching is in place it doesn't load the env]
"If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files. Once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null." - Laravel 7.x Docs - Configuration - Configuration Caching
Laravel 7.x Docs - Configuration - Accessing Configuration Values config()
Laravel 7.x Docs - Configuraiton - Retrieving Environmental Configuration env()

Related

Laravel - Sever is not reading the files from the path

I'm facing a problem with my Laravel application. It is deployed on the server and uses nginx as the main web server.
I am unable to read two files from the path I set in the deployment server, but on the local environment, it is working fine. These two files are confidential, one is .crt file and second is .pem file. I placed both of these files in laravel-app/app/Certificates directory.
laravel-app/app/Certificates/test2-2023_cert.pem
laravel-app/app/Certificates/curl-bundle.crt
The file path in .env is set like this:
PEM=/Certificates/test2-2023_cert.pem
CRT=/Certificates/curl-bundle.crt
My config/services file:
<?php
return [
'pay' => [
'pem' => app_path() . env('PEM', ''),
'crt' => app_path() . env('CRT', '')
]
];
My Controller construct function:
public function __construct()
{
$this->pem = config('services.pay.pem');
$this->crt = config('services.pay.crt');
}
It is returning the following path on server:
/var/www/laravel-app/app/Certificates/test2-2023_cert.pem
/var/www/laravel-app/app/Certificates/curl-bundle.crt
but the server is not loading the file and gives me an error response in the API call. What I'm doing wrong?

Laravel8 laravelcollective/remote can I create a dynamic connection

I'm migrating our inhouse backup app onto Laravel8, so far so good. I'm interested in using the laravelcollective/remote facade (SSH) to ssh onto the remote server and run some commands which it looks like this would be very good at (rather than using php exec() methods the current backup app uses).
My question however is, can i build an array/object from the database and use these details as a connection without having to manually maintain the config/remote.php file? Maintaining this with any server changes will be a nightmare to maintain as we frequently update users and sites are added removed on a regular basis! any ideas? As mentioned we are storing the ssh creds in the database which is populated via a connection form within the app.
I've built a simple test function in a controller and stepped into this with my debugger. I expected to see the array/object which is created from the config/remote file and was planning to just add new items but i couldn't find any array/objects containing the default empty production config set as default in the config/remote.php file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use SSH;
class SecureServerController extends Controller
{
public function test() {
SSH::into()->run([
'cd /var/www',
'git pull origin master'
], function($line)
{
echo $line.PHP_EOL;
});
}
}
The following is the route used:
use App\Http\Controllers\SecureServerController;
Route::get('/test', [SecureServerController::class, 'test']);
thanks
*** EDIT ***
SO I had a look at the code for the SSH facade and found I could create a config file and pass this via the connect function:
$config = [
'host' => '123.123.123.123',
'username' => 'the-user',
'password' => 'a-password'
];
SSH::connect($config)->run([
'cd /var/www',
'git pull origin master'
], function($line)
{
echo $line.PHP_EOL;
});
However i see no way to use any port except 22. almost all our servers use a non default port as an additional level of obfuscation.

Laravel Dusk: how to use in-memory DB for testing

What I've been trying is to use in-memory database while testing with Laravel Dusk.
Here we have a file, .env.dusk.local, with the following values.
DB_CONNECTION=sqlite
DB_DATABASE=:memory:
Here is a snippet of a browser testing file.
class ViewOrderTest extends DuskTestCase
{
use DatabaseMigrations;
/** #test */
public function user_can_view_their_order()
{
$order = factory(Order::class)->create();
$this->browse(function (Browser $browser) use ($order) {
$browser->visit('/orders/' . $order->id);
$browser->assertSee('Order ABC'); //Order name
});
}
}
When php artisan dusk is executed, Dusk starts browser testing.
However, Dusk seems to be accessing my local DB, because there is an order name on the testing browser which only exists in my local DB, while 'Order ABC' is expected to be displayed on the browser.
According to the doc, Laravel Dusk allows us to set the environmental variables.
To force Dusk to use its own environment file when running tests, create a .env.dusk.{environment} file in the root of your project. For example, if you will be initiating the dusk command from your local environment, you should create a .env.dusk.local file.
I don't feel that Dusk is accessing the seperate DB.
Any advice will be appreciated.
You can't use :memory: database while Laravel dusk browser testing. Your development server and dusk testing runs on separate processes. dust test cannot access to memory of process running on development server.
Best solution it to create sqlite file database for testing.
'sqlite_testing' => [
'driver' => 'sqlite',
'database' => database_path('sqlite.testing.database'),
'prefix' => '',
],
Create sqlite.testing.database file inside database folder.
Make sure to run development server before running tests using
php artisan serve --env dusk.local
You need a connection in config/database.php
'sqlite_testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
Then in your phpunit.xml file use:
<env name="DB_DEFAULT" value="sqlite_testing" />
or in your tests use:
putenv('DB_DEFAULT=sqlite_testing');
Don't forget to use the RefreshDatabase trait to reset the database before each test.

Laravel, 'env' in database config

i was configuring my sqlite connection in framework laravel. While using 'php artisan migrate' command i've got a message that there is no connection.
I changed this two lines of my code
'default' => env('DB_CONNECTION', 'sqlite'),
'database' => env('DB_DATABASE', database_path('database.sqlite'))
to
'default' => 'sqlite',
'database' => database_path('database.sqlite'),
Now everything works fine, but my question is what does the ENV function do??
Am i right to delete this?
In Laravel env() is the helper function, which gets the value of an environment variable or returns a default value:
Example:
$env = env('DB_CONNECTION');
// Return a default value if the variable doesn't exist...
$env = env('DB_CONNECTION', 'sqllite');
To give your application a speed boost, you should cache all of your configuration files into a single file using the php artisan config:cache. Which cache the env values as well, so in order to take effect of cached values changes one must have to clear it by using php artisan cache:clear
The env function gets the value of an environment variable from your .env file or returns a default value which is the second argument.
For more information read: Documentation

Laravel 4.2 Environments on the same Server

I've to deploy several instances of a Laravel app to a unique server. Each instance requires a different database configuration. The default Laravel's environment configuration based on hostnames doesn't work for me because all the apps are going to be on the same server, so there's no way to tell which config fiel to use. Here is my bootstrap/start.php file:
$env = $app->detectEnvironment(array(
'development' => array('Ariels-MacBook-Pro.local'),
'server' => array('srv-hostname'),
));
It would be great that I can define the environment based upon a domain (because my apps area gonna be on diferent domains), so in this way I can define a different config for each domain (hosted on the same server)
Any ideas?
Laravel's detectEnvironment method has a nify feature where you can progamatically determine the current enviornment with a closure. For example, this would configure Laravel to always use the local enviornment.
$env = $app->detectEnvironment(function()
{
return 'local';
});
The domain name should be somewhere in $_SERVER, so something like this untested pseudo-code should get you what you want.
$env = $app->detectEnvironment(function()
{
switch($_SERVER['HTTP_HOST'])
{
case: 'example.com':
return 'production';
case: 'another.example.xom':
return 'production';
default:
return 'local'; //default to local
}
});
My option, in file app/config/database.php add this line at the end
'enviorement' => 'local',
// 'enviorement' => 'development', // this is for dev
// 'enviorement' => 'production', // this is for production
and then access from your controller with this
$env = Config::get('database.enviorement');
echo $env;
database.php file is different, you have for ur local another for developemet server and another for producction because there is the "database conection" so i used it to implicit write the enviorement.
Have fun.

Categories