Passing information to template from multiple databases with Laravel - php

I have to pass multiple databases info with Laravel. I always do this:
public function get_view(){
$myinfo = MyDatabases::where('id',Auth::user()->id)->get();
return view('auth.view')->with('myinfo',$myinfo);
}
I need to pass info from other databases. Is there a way to do this?

You have some db in your file app/config/database.php ?
'connections' => [
'mysql1' => [
],
'mysql2' => []
]
You can use :
\DB::connection('mysql1')->table()->where(....)
\DB::connection('mysql2')->table()->where(....)
and you can create some help function or Facade, where you can aggregate this queries

Related

How to dynamically pass the variable name into the model in the laravel provider's model config.php file

For instance let's say the
'''
$model_name = 'student_table';
'''
'providers' => [
'users' => [
'$model_name' => [
'driver' => 'eloquent',
'model' => App\Models\.$model_name.::class
]
]
]
The problem is that laravel fires an unexpected '.' expecting identified (T_STRING)
And I need to insert the model name dynamically because there lot of database tables to connect with. Any other solution pls
that's not going to work, providers are loaded way before the controller is.
maybe if you use a config table in database that orient users to own specific auth table.
https://laravel.com/docs/5.7/lifecycle
That is a syntax error.
After App\Models\ you can't have ., It expects you to write the class name next.
Try this:
'providers' => [
'users' => [
'$model_name => [
'driver'=> 'eloquent',
'model' => "App\Models\\" . $model_name
]
]
]
Notice you don't need ::class anymore as you have the full namespace of the class in string.

TYPO3 v10 - Getting feUser Object using context API in eID_include

Code that i used and need to update for V10
$this->feUser = EidUtility::initFeUser();
When using the following code (a random) controller, the context gives me the correct login feUser object.
$context = GeneralUtility::makeInstance(Context::class);
$user = $context->getAspect('frontend.user');
DebuggerUtility::var_dump($user);
When using the same code in an eID_include class No userObject is given.
Specificly in the following class
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['FileDumpEID.php']['checkFileAccess']['xxx'] = My\Class\Hooks\FileDumpHook:class
Is there a need of bootstrapping context?
Since the TYPO3\CMS\Frontend\Middleware\EidHandler middleware is executed before the TYPO3\CMS\Frontend\Middleware\FrontendUserAuthenticator middleware in the middlewares order i dont think, that this is possible.
If you need parts of the frontend handling you either can add an own middleware with depend of TYPO3\CMS\Frontend\Middleware\FrontendUserAuthenticator or use an page Object in typoscript.
I had the same problem. You may change the order of Middlewares: https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/RequestHandling/Index.html
I've created a new file RequestMiddlewares.php inside the "Configuration" directory of my extension:
<?php
return [
'frontend' => [
'typo3/cms-frontend/eid' => [
'disabled' => true
],
'typo3/cms-frontend/eid-new' => [
'target' => \TYPO3\CMS\Frontend\Middleware\EidHandler::class,
'after' => [
'typo3/cms-frontend/tsfe',
],
'before' => [
'typo3/cms-frontend/prepare-tsfe-rendering',
]
]
]
];
You have to flush TYPO3 and PHP Cache and check the ordering in "Configuration" backend module (select "HTTP Middlewares (PSR-15)").
With this setup it is possible to get the context property 'frontent.user'
$context = GeneralUtility::makeInstance(Context::class);
if($context->getPropertyFromAspect('frontend.user', 'isLoggedIn')) {

Yii2 gridview how to get related model only once for more attributes

I have a Yii2 gridview. Now if I want to show related data using lazy loading it seems like this:
[
'attribute' => 'relatedName',
'value' => function ($model) {
return (($rel = $model->getRelated()->one()) ?
$rel->name : '')
;}
],
If I want to show an additional attribute of the same related model, I can add a new attribute like above, but then Yii will be selecting the same related model once again for each row of data.
Without eager loading (unfortunately is not possible in this case) is it possible to force yii to select related only once for each row and make $rel reusable in many columns? Thanks in advance!
$model->getRelated() returns ActiveQuery object. If you want to load a related model once you can do it with using $model->related instead of $model->getRelated()->one(). For example:
[
'attribute' => 'relatedName',
'value' => function ($model) {
return is_null($model->related) ? '' : $model->related->name;
}
],
Or more simple way
[
'attribute' => 'related.name',
],

Laravel Guzzle Request gets wrong DB Connection

I am trying to make a request from one Laravel project to another. The issue that I am getting is that the second Laravel is using the first Laravel Database Connection. So it is complaining that a table does not exist.
Here is the code that I am using.
$data = ['test' => 'foobar'];
$client = new \GuzzleHttp\Client();
$url = getenv('API_BASE') . 'stock-list';
$res = $client->request('POST', $url, [
'headers' => [
'X-Public' => getenv('API_PUBLIC'),
'X-Hash' => ApiService::Encrypt(getenv('API_PRIVATE'), json_encode($data)),
],
'json' => $data,
'http_errors' => false,
]);
echo "<pre>" . print_r($res->getBody()->getContents(), true) . "</pre>";
Has anyone ever come across something like this?
The way to fix this as I am running both Laravel projects on the same server, is to change the environment variable names in the .env file.
DB_DATABASE=XXXX
becomes
XXX_DB_DATABASE=XXXX
This needs to be done on one of the Laravel setups then it all works properly.
You can change the default db connection runtime like this:
So let's say you have
1 security db with credentials that is the default db design time.
1 or more databases containing data for 1 or more users.
You log in using the security db and based on the user change the default db to the data db.
config(['database.connections.data' => array(
'driver' => 'sqlsrv',
'host' => $connection['Database_Server'],
'database' => $connection['Database_Name'],
'username' => $connection['Database_User'],
'password' => $connection['Database_Password']
)]);
DB::setDefaultConnection('data');
If you don't need such flexibility you can define the connection per model:
class A extends Model {
protected $connection = 'security';
protected $table = 'A';
}

How to use authentication for multiple tables in Laravel 5

Sometimes, we'd like to separate users and admins in different 2 tables.
I think it is a good practice.
I am looking if that is possible in Laravel 5.
Before reading the following, you are supposed to have basic knowledge on ServiceProvider, Facade and IoC in Laravel 5. Here we go.
According to the doc of Laravel, you could find the Facade 'Auth' is refering to the Illuminate\Auth\AuthManager, which has a magic __call(). You could see the major function is not in AuthManager, but in Illuminate\Auth\Guard
Guard has a Provider. This provider has a $model property, according to which the EloquentUserProvider would create this model by "new $model". These are all we need to know. Here goes the code.
1.We need to create a AdminAuthServiceProvider.
public function register(){
Auth::extend('adminEloquent', function($app){
// you can use Config::get() to retrieve the model class name from config file
$myProvider = new EloquentUserProvider($app['hash'], '\App\AdminModel')
return new Guard($myProvider, $app['session.store']);
})
$app->singleton('auth.driver_admin', function($app){
return Auth::driver('adminEloquent');
});
}
2.Facade:
class AdminAuth extends Facade {
protected static function getFacadeAccessor() { return 'auth.driver_admin'; }
}
3. add the alias to Kernel:
'aliases' => [
//has to be beneath the 'Auth' alias
'AdminAuth' => '\App\Facades\AdminAuth'
]
Hope this could be helpful.
I have created a laravel package where you can handle multiple authentication.
Step 1 : Composer require
Firstly, composer require the multiauth package
composer require sarav/laravel-multiauth dev-master
Step 2 : Replacing default auth service provider
Replace
Illuminate\Auth\AuthServiceProvider::class
with
Sarav\Multiauth\MultiauthServiceProvider
in your config/app.php file
Step 3 : Modify auth.php
Modify your config/auth.php file to something like this
'multi' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
'table' => 'users'
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
'table' => 'admins'
]
],
Thats it! Now you can try multiple authentication by passing the user as first parameter. For example
\Auth::loginUsingId("user", 1); // Login user with id 1
\Auth::loginUsingId("admin", 1); // Login admin with id 1
// Attempts to login user with email id johndoe#gmail.com
\Auth::attempt("user", ['email' => 'johndoe#gmail.com', 'password' => 'password']);
// Attempts to login admin with email id johndoe#gmail.com
\Auth::attempt("admin", ['email' => 'johndoe#gmail.com', 'password' => 'password']);
For more detailed documentation
http://sarav.co/blog/multiple-authentication-in-laravel/
http://sarav.co/blog/multiple-authentication-in-laravel-continued/

Categories