Using Laravel Facades outside Laravel - laravel

I have a Laravel application which I use as an API to a much larger application built in Joomla. I really love using Laravel and decided to use Eloquent within the Joomla application. I got this working by importing the bootstrap\autoload.php file in the Laravel application and creating a Capsule
require JPATH_ROOT.'/../laravel_app/bootstrap/autoload.php';
$capsule = new Capsule();
$config = new JConfig();
$capsule->addConnection([
'driver' => 'mysql',
'host' => $config->host,
'database' => $config->db,
'username' => $config->user,
'password' => $config->password,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => $config->dbprefix,
'strict' => false
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
This works great and I can use Eloquent. It loads the Eloquent models from the app directly.
What I want to know is how I get the rest of the Laravel app working inside my Joomla app, including using Facades.
For example I have the use of Config.get('key') within one of the Eloquent models, works fine when called in Laravel, but throws and error when called in Joomla.
Fatal error: Class 'Config' not found in laravel_app/app/Model.php on line 192

I have looked at laravel_site/public/index.php to see how it initiates the application and so far so good this seems to be a working solution:
require JPATH_ROOT.'/../laravel_site/bootstrap/autoload.php';
$app = require_once JPATH_ROOT.'/../laravel_site/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Http\Kernel');
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
//$response->send();
//$kernel->terminate($request, $response);
Facades now appear to be working fine. I've purposely left out $response->send(); and $kernel->terminate($request, $response); so that the routing does not take place and override Joomla's own routing.
I also no longer need to instantiate the Capsule as Laravel is doing that for me now.
I haven't tested this fully so I do not know how robust it is or what features will work but all is good so far.

Related

Using Payment-Element in Stripe and Laravel

We have everything working in Laravel using Stripes card-element. We want to start using the new payment-element. We are currently using the setup intent.
Following the guide: https://stripe.com/docs/payments/payment-element/migration
Stripe says to add payment methods like so:
$intent = \Stripe\SetupIntent::create([
'customer' => $customer->id,
'payment_method_types' => ['card', 'bancontact', 'ideal'],
]);
In Laravel we currently have it setup like so:
return view('payment.payment')->with([
'services' => $services,
'intent' => $user->createSetupIntent()
]);
How do we pass payment_method_types to the Laravel cashier's createSetupIntent() method?

"Class 'App\Game\User' not found" even with changed providers

When i try to register an account it comes up with this error " class App\Game\user" not found
I have changed the providers auth.php to App\Game\User::class,
and i have changed the name space on the user.php to namespace App\Game;
Game.php does exist (however nothing is coded in it and im wondering if this is the problem?)
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Game\User::class,
],
the browser highlights the return line in this part of the RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Edit: I didn't realize it meant folders in the naming convention and put them into the appropriate folders. Thank you. My apologies i couldn't find a question relating to this on stackover flow and ive only just started on laravel
First of all if you have something like App\Game\User::Class
That means you will have a game folder inside the app folder and then user.php file in that Game folder with. You can use the full namespace to call the class like \App\Game\User if it's still not working try to run composer dump-autoload to regenerate the composer files.
Laravel model stores under app>user.php and make sure your file does exist in app>game folder

Dynamic env-files (multiple databases) and artisan commands

I have a large project which will have each customer on their own separate database. To get this to work we use a custom .env-loader that loads each customers .envby checking the customers subdomain (unique to each customer).
However, of course this doesn't work with artisan commands. For instance, when I want to migrate, I will need to migrate all databases at once. So I've set up an Artisan command that fetches the .env-files and loop through them and then calls the default artisan migrate. But it is not working as expected.
I've tried everything; for instance:
$dotenv = new Dotenv('/env', '.test.env');
$dotenv->overload();
And:
app()->useEnvironmentPath('/env');
app()->loadEnvironmentFrom('.test.env');
And even:
config('database.connections.mysql.database', 'test_database');
As soon as I run $this->call('migrate'); the app defaults to the default .env and ignores all customizations at runtime. Does anyone have an idea on how I can overload the migration commands choice of database?
Note: I know that I can manually setup multiple connections in config/database.php (for instance like: Overriding Default Laravel database configuration for artisan migrate commands), however, image a few dozen customers and this would not be viable.
I had to do something similar with SQLite database that were being created by the console commands, and the only way I could get the migrations to run was by creating a database config on the fly:
Config::set('database.connections.'.$config_key, array(
'driver' => 'sqlite',
'database' => storage_path($database_name),
'prefix' => '',
));
And then I would call the migrate command:
Artisan::call('migrate', [
'--database' => $config_key,
'--path' => 'database/offline/'.$type.'/migrations',
]);
After a whole lot of issues I was able to sort it this way;
In Laravel 5 there seem to be a difference in Config::set(), config('config',['key' => 'value]) and config()-set('config', ['key' => 'value']).
After a lot of testing different variant we managed to get a solution this way;
$connection = 'connection';
$iterator = 0;
foreach ($files as $file) {
App::useEnvironmentPath('/env');
App::loadEnvironmentFrom('.file.env');
// Create a new connection "on the fly"
config()->set('database.connections.' . $connection . '_' . $iterator, [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
]);
// Call regular migration command
$this->call('migrate', ['--force' => true, '--database' => $connection . '_' . $iterator]);
$iterator++;
}
This manages to set multiple new connections to the MySQL-database, and then seed each one of them.
Thanks to #David Allen here for the inspiration.

CI Merchant no output

I am trying to use CI Merchant library for codeignator
here is my code:
$this->load->library('merchant');
$this->merchant->load('paypal_express');
$settings = array(
'username' => 'api.sandbox.paypal.com',
'password' => 'AQHaXxDW3dlKDRDJ7lDtGr4w8-reNNfvPFUKmEr9npMzYjZ2WIbfqqI3VL2C',
'signature' => 'EMbUfhBCqBZw8hhH6q8VZT_53-xwoOs6_lotS68I7qrY5iyHPLgDitrsAZj5',
'test_mode' => true);
$this->merchant->initialize($settings);
$params = array(
'amount' => 100.00,
'currency' => 'USD',
'return_url' => 'https://www.example.com/checkout/payment_return/123',
'cancel_url' => 'https://www.example.com/checkout');
$response = $this->merchant->purchase($params);
echo '<pre>';
print_r($response);
echo '</pre>';
but when I run it local here is result:
Merchant_response Object
(
[_status:protected] => failed
[_message:protected] => error setting certificate verify locations:
CAfile: C:\xampp\htdocs\egyptianornaments\application\config/cacert.pem
CApath: none
[_reference:protected] =>
[_data:protected] =>
[_redirect_url:protected] =>
[_redirect_method:protected] => GET
[_redirect_message:protected] =>
[_redirect_data:protected] =>
)
and when I run on the server I get a blank page
so what I am doing wrong?
Looks like your code is setup to use a certificate instead of the signature method, but your servers don't have the SSL cert installed and configured to work with PayPal, which is really sort of a pain to deal with anyway. I would recommend switching to the signature method and then you won't have to mess with that at all.
I'm not familiar with the library you're using, but there must be some way to set that. You might also want to take a look at my own CodeIgniter library for PayPal that is pretty popular.
I've actually stopped maintenance of that CI specific library, though, because I now have my general PHP library for PayPal updated for PHP 5.3+ and working with Composer / Packagist, which allow you to use it in CodeIgniter or any other framework.
As of today, the CI specific library isn't far behind, but again, I'm not updating it anymore. I'm only maintaining the general version now since it works everywhere.
Anyway, it makes every PayPal API call very simple for you.

Using Eloquent ORM from Laravel 4 outside of Laravel

I created a folder 'eloquent' to start testing/learning the component, and my composer.json file is:
{
"require": {
"php": ">=5.3.0",
"illuminate/database": "4.0.*"
}
}
Below is my test.php file, with credentials removed. It works great, until I add ->remember(10) into the command. I'd like to look into adding the Illuminate Cache next then, if that's what's needed to start using ->remember(). Is anyone aware of any blog posts or tutorials on doing something like this?
<?php
/**
* Testing Laravel's Eloquent ORM
* #see https://github.com/illuminate/database
* #see http://laravel.com/docs/database
*/
require 'vendor/autoload.php';
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection(array(
'driver' => '',
'host' => '',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
));
//$capsule->bootEloquent();
$capsule->setAsGlobal();
$name = Capsule::table('user')->where('id', 123 )->remember(10)->get();
var_dump( $name );
// PHP Fatal error: Uncaught exception 'ReflectionException' with message 'Class cache does not exist'
I'm not sure what the next step is to get ->remember() working. I tried adding illuminate/cache to the composer.json file and updated. I wasn't sure how to use it with Eloquent, outside of Laravel.
saff33r is right, but just to help someone like me that need "file" cache this is how to:
in your composer.json
"illuminate/cache": "4.0.*",
"illuminate/filesystem": "4.0.*",
in your boot file:
use \Illuminate\Database\Capsule\Manager as Capsule;
use \Illuminate\Cache\CacheManager as CacheManager;
use \Illuminate\Filesystem\Filesystem as Filesystem;
...
$container = $capsule->getContainer();
$container['config']['cache.driver'] = 'file';
$container['config']['cache.path'] = __DIR__ . '/uploads/cache/eloquent';
$container['config']['cache.connection'] = null;
$container['files'] = new Filesystem();
$cacheManager = new CacheManager($container);
$capsule->setCacheManager($cacheManager);
$capsule->bootEloquent();
It should already be pulling in "illuminate/cache", look in vendor and you should see it there.
You need to setup the cache manager, then pass that through by calling
$capsule->setCacheManager(CacheManager $cache);
I've not looked under the hood for details on how to do this but hopefully this will be enough details to get you going forward.
Edit:
Here's what you need to add to get it working:
use Illuminate\Cache\CacheManager as CacheManager;
$container = $capsule->getContainer();
$container->offsetGet('config')->offsetSet('cache.driver', 'array');
$cacheManager = new CacheManager($container);
$capsule->setCacheManager($cacheManager);
Obviously feel free to change the Cache Driver used but keep in mind that changing the Cache Driver will require adding the extra required settings.
Check out https://github.com/Luracast/Laravel-Database it provides full eloquent support outside laravel including artisan migrations and more
4.2 branch contains laravel 4.2.* components
5.2 branch contains laravel 5.2.* components
Disclosure: I'm the author of the above repository

Resources