Refactored code: PDO connection is removed, replaced by laravel connection. Combine most queries to one compact query. Some variables are removed, renamed, or added.