How to access Session data from database - laravel

I want to access session data from database. Currently, I have changed default setting in session.php to database so that I can capture all the session columns in DB. But now I want to access these in my code. Do I need to create some session model or it's present out of the box just like user.php. Please help me.

You should create sessions table with these commands:
php artisan session:table
composer dump-autoload
php artisan migrate
Or you could manually create migration and run it, an example from documentation:
Schema::create('sessions', function ($table) {
$table->string('id')->unique();
$table->text('payload');
$table->integer('last_activity');
});
After doing that, you can just use sessions as usual with Session:: facade or sessions() helper:
session()->flash('message', 'Success!');
Update
If you need to access table data directly, you could do this:
DB::table('sessions')->get();
Or you could create SessionData() model and do this:
SessionData::all();

Related

Laravel Passport : How to createToken in specific postgres schema

I'm currently looking to build SaaS application with Laravel APIs and Postgres as database
Every customer will have its own schema and I migrate the tables and data in its own schema.
Endpoint : https://google.<domain-name>.com/login
Wrote a middleware which will activate the schema depending on the sub-domain and this seems to working fine in PassportController.php
Currently, I'm having trouble login in a user as createToken is trying to insert a record in
public.oauth_access_tokens
but it should in fact create a record in
google.oauth_access_tokens (google is my schema)
Here is the code which is failing and I could able to get user object when I try to print auth()->user()
$accessToken = auth()->user()->createToken('authToken')->accessToken;
How can I use createToken in specific schema?
Update
I just figured out that it works if I change
protected $table = 'oauth_access_tokens';
to
protected $table = 'google.oauth_access_tokens';
in vendor/laravel/passport/Token.php (model) [I know, we should not be changing anything in vendor files].

Define database connection for supervisor

In my laravel 8 app, I have three database connections, viz Database-0, Database-1, Database-2.
Database-0 used for authenticating users so it has users table and Laravel Auth method retrieve user using this connection as I have set it in passport configuration file.
Database-1 and Database-2 connection used for all other purposes except authentication.
In my users table I have just two users with email first_user#example.com and second_user#example.com
When user is logged in with first_user#example.com then Database-1 should be used and if user is logged in with second_user#example.com then Database-2 should be used.
To acheive this I have created a middleware and register it in $middleware group so it run for all the request. In this middleware, I am checking the logged in user email and based on that I am setting database connection.
Up until now everything works perfectly
Now I have a job of that is being queued and I am using database as my QUEUE_CONNECTION. so my job stored in database jobs table. I have configured supervisor for processing this job.
Now the problem is when supervisor make query to retrieve job, my middleware doesn't get called and it throws following error
invalid catalog name: 1046 No database selected (SQL: select * from jobs where ....)
So my question is how can I set database connection for supervisor to choose from database when retrieving jobs?
middleware
public function handle(Request $request, Closure $next)
{
$auth_email = Auth::guard('api')->user()?->email;
if ($auth_email === 'first_user#example.com') {
config(['database.connections.fe_mysql.database' => 'Database-1']);
} elseif ($auth_email === 'second_user#example.com') {
config(['database.connections.fe_mysql.database' => 'Database-2']);
}
return $next($request);
}
supervisor config
[program:queue-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/laravel-project/artisan queue:work --queue=admin
autostart=true
autorestart=true
user=root
numprocs=8
redirect_stderr=true
stopwaitsecs=7200
stdout_logfile=/var/www/html/laravel-project/worker.log
Use the config() function to set extra or overwrite existing connection settings.
config(['database.connections.mynewconnection' => {settings here}]);
Keep in mind that these settings are cached. So when you need to use the new settings, purge the DB cache for the connection you're gonna use.
DB::purge('mynewconnection');
You can also manipulate the default connection that is used. This can come in handy if you wish to use migrations over different connections and keep track of them with a migration table within the used connection. Or other cool stuff ofcourse...
DB::setDefaultConnection('mynewconnection');

How to maintain two migration tables in Laravel Migration

I'm writing a custom migration and I need to maintain those migrations in a separate migration repository table. I override DatabaseMigrationRepository and replace the migration repository function as follows
public function registerRepository()
{
$this->app->bindShared('migration.repository', function($app)
{
$table = $app['config']['database.cf_custom_migrations'];
return new CustomDatabaseMigrationRepository($app['db'], $table);
});
}
And I have registered my custom migration in artisan.php.
But when I call the custom migration command its execution is based on the Default Migration command.
Have anyone tried this before? How can run the Custom Migration command on Custom Migration table?
create a custom command instead of using migrate which is default to laravel.
use that custom command to run your custom migrations.
hope it helps

How to globally prevent saving to database in Laravel 5

I made a PHP script in Laravel and now I want to show demo to my buyers. Since I don't want them to make any changes to the database, I was wondering if there is a way to globally disable any saving to the database?
If you have a BaseModel that extends Laravel's default Eloquent model class. And all of your applications models extend that BaseModel you can add the following to it:
public static function boot()
{
parent::boot();
static::saving(function($model)
{
return false;
});
}
This will intercept any creating or updating events from Eloquent.
This may be the technical answer for your question, but ideally just backup your db and restore it after showing to your buyers.
The easiest thing will be to create a mysql user that hasn't permissions to insert. Use the following mysql statement to create the user and use this user as the user in your database setting. I don't think there's a global method for this in laravel.
GRANT SELECT ON [database name].[table name] TO ‘[username]’#'%’;
This way, your user can view everything, but isn't able to save a bit.

Create tables in Laravel 4 with Schema Builder without Migrations on shared hosting

Well, I have a web application and I want to create a teable with Schema Builder, and I cannot Create a migration in a shared hosting, what can you suggest to make a table with Schema?
Schema::create('users', function($table)
{
$table->increments('id');
});
ps. I want to use specifically Laravel's Schema Builder to create tables
You can solve this by creating migrations and a install route. From which you can call some thing like this
Artisan::call('migrate');
for more info look at this Run Artisan Commands Form Route or Controller
Have you tried using Laravel's Routing to run schema builder ?
Route::get('/', function () {
Schema::create('table', function($table) {
$table->increments('id');
});
return "done.";
});

Resources