How to use Solarium with Laravel? - laravel-5

I've included Solarium as required on composer.json, did composer install and everything went fine.
However, when I try to create a client stance, I get an error:
Class 'Solarium\Client' not found
The code I'm using goes like this:
public function __construct()
{
$config = array(
'endpoint' => array(
'localhost' => array(
'host' => '127.0.0.1',
'port' => 8983,
'path' => '/solr/my_solr_instance',
)
)
);
$this->client = new \Solarium\Client($config);
}
Any ideas on how to fix this?

After installing solarium in laravel ..
create a file solr.php in config
return [
'endpoint' => [
'Collection' => [
'host' => '192.168.0.1',
'port' => '8983',
'path' => '/solr',
'core' => 'collection1'
],
]
];
IN your controller construction initiate client object
// create a client instance
$this->client = new \Solarium\Client();
$this->endpoint = $this->client->createEndpoint(Config::get('solr.endpoint.Collection'));
In search function
$query = $this->client->createSelect();
$query->setQuery("*:*");
$resultset = $this->client->select($query, $this->endpoint);

I have a new approach for this initiate client from the controller.
I have found this solution here as below it is not good to post complete code.
https://universaldetails.com/details/how-to-use-php-solarium-in-a-laravel-project
I have tried it and tested also so will help you.

Related

Query parameter binding issue with illuminate/database and illuminate/queue

I'm using Illuminate\Queue outside of a Laravel app inside an add-on for a CMS. So the only instances of Laravel or Illuminate are these packages that I've required:
"illuminate/queue": "^8.83",
"illuminate/bus": "^8.83",
"illuminate/contracts": "^8.83"
I'm first trying to use the Database for the queue as the default driver since the CMS is database driven, then provide options to SQS etc. I've setup everything so the migrations create my queue tables and everything seems to be wired together when I make the following call to push something to the queue.
/** #var \Illuminate\Queue\QueueManager $queue */
$queue->push('test', ['foo' => 'bar']);
Then it ends in the following error. The parameter bindings are not working or something. It's leaving the ? in the values list.
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"exp_dgq_jobs" ("queue", "attempts", "reserved_at", "available_at", "created_at"' at line 1 (SQL: insert into "exp_dgq_jobs" ("queue", "attempts", "reserved_at", "available_at", "created_at", "payload") values (default, 0, ?, 1674567590, 1674567590, {"uuid":"6bf7a17e-dda3-4fed-903a-8714e5a2d146","displayName":"test","job":"test","maxTries":null,"maxExceptions":null,"failOnTimeout":false,"backoff":null,"timeout":null,"data":{"foo":"bar"}}))
I've step debugged the whole request and it feels like a bug, but then again this is really the first time I've used Laravel or one of it's packages, so maybe I'm missing something? This function explicitly sets reserved_at to null, and the Connection->prepareBindings() method doesn't do anything with the ?, it just leaves it as that value, so the query fails.
protected function buildDatabaseRecord($queue, $payload, $availableAt, $attempts = 0)
{
return ['queue' => $queue, 'attempts' => $attempts, 'reserved_at' => null, 'available_at' => $availableAt, 'created_at' => $this->currentTime(), 'payload' => $payload];
}
What am I missing? Everything just looks right to me an I'm kind of at a loss. I'm making this with PHP 7.4 in mind (for the time being). Maybe I'll try 8.1 to see if that changes anything with the Illuminate packages. Using MySQL 8 too.
Update: potentially relevant screenshot just before the error.
Update 2: I tried PHP 8.1 and latest Laravel 9 packages, didn't make a difference.
For more clarity on how I"m creating my QueueManager:
<?php $queue = new Queue;
$queue->addConnection([
'driver' => 'database',
'table' => ee('db')->dbprefix . 'dgq_jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
]);
$databaseConfig = $provider->make('DatabaseConfig');
$queue->addConnector('database', function () use ($databaseConfig) {
$pdo = new PDO(
sprintf('mysql:host=%s; dbname=%s', $databaseConfig['host'], $databaseConfig['database']),
$databaseConfig['username'],
$databaseConfig['password']
);
$connection = new Connection($pdo);
$connectionResolver = new ConnectionResolver(['default' => $connection]);
$connectionResolver->setDefaultConnection('default');
return new DatabaseConnector($connectionResolver);
});
return $queue->getQueueManager();
I was able to reproduce the error you were seeing. I haven't looked too deeply but I think it may be due to the PDO object not setting up the connection exactly as the Illuminate Queue library expects.
This modification to using the Illuminate\Database library to create the connection solved the issue in my test environment:
$database = new \Illuminate\Database\Capsule\Manager;
$queue = new \Illuminate\Queue\Capsule\Manager;
$database->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'db_name',
'username' => 'username',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);
$queue->addConnector('database', function () use ($database) {
$connection = $database->getConnection();
$connectionResolver = new \Illuminate\Database\ConnectionResolver(['default' => $connection]);
$connectionResolver->setDefaultConnection('default');
return new \Illuminate\Queue\Connectors\DatabaseConnector($connectionResolver);
});
$queue->addConnection([
'driver' => 'database',
'table' => 'jobs_table',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
]);
$queue->getQueueManager()->push('SendEmail', ['message' => 'test']);

BlueFeatherGroup eloquent-filemaker connection problem

I'm using https://github.com/BlueFeatherGroup/eloquent-filemaker in a Laravel Project to get data from a FileMaker database.
I use a MySQL as default connection in my project, but I need a second connection to a FileMaker Server.
I created in database.php config file a new conn:
'filemaker' => [
'driver' => 'filemaker',
'host' => 'myfmhost',
'database' => 'FMdatabase',
'username' => 'FMUser',
'password' => 'MFPass',
'prefix' => '',
'version' => 'vLatest',
'protocol' => 'https',
],
I created a model "tabla" as follows:
use BlueFeather\EloquentFileMaker\Database\Eloquent\FMModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class tabla extends FMModel
{
use HasFactory;
protected $connection= 'filemaker';
protected $fillable = [ ];
protected $layout = 'tabla';
}
In my Controller:
$data = tabla::all();
dd($data);
and I get this error:
Argument 1 passed to
BlueFeather\EloquentFileMaker\Database\Query\FMBaseBuilder::__construct()
must be an instance of
BlueFeather\EloquentFileMaker\Services\FileMakerConnection, instance
of Illuminate\Database\MySqlConnection given
But if I do this in my controller (Query Builder aproach):
$data = FM::connection('filemaker')->layout('tabla')->get();
dd($data);
It works ok!
What am I doing wrong? Is it possible to use filemaker conn when using Eloquent if it's not the default project connection ?
Thanks in advance!!

Making an OAuth request with Laravel for Stripe

I was translating following PHP code:
$person = \Stripe\Account::createPerson(
'{{CONNECTED_ACCOUNT_ID}}', // id of the account created earlier
[
'person_token' => $token,
]);
To:
$making_user = $stripe->account()->persons()->create(
$request[0], // id of the account created earlier
[
'person_token' => $request[1],
]);
Above Laravel code works find without any issue. Does anyone have any idea that what can be the equivalent Laravel syntax of the following:
$response = \Stripe\OAuth::token([
'grant_type' => 'authorization_code',
'code' => 'ac_123456789',
]);
I'm using following as equivalent, but it is giving me error of invalid method "oauth"
$making_account = $stripe->oauth()->create([
'grant_type' => $request['code'],
'code' => 'ac_123456789',
]);
I'm not finding anywhere its syntax anyone have an idea what will be the Laravel syntax of making Oauth call?
This worked for me.
$stripe = new \Stripe\StripeClient('SECRET_KEY_HERE');
$response = $stripe->oauth->token([
'grant_type' => 'authorization_code',
'code' => 'CODE_HERE'
]);

Laravel download not working

In my application I have the need to:
upload a file
store information in the db
store the file in a local or remote filesystem
listing all the db rows with a link to download the file
remove the file from the db and from the filesystem
I am trying to develop the 4th but the solutions found here and here don't work for me.
My filesystem.php is:
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'visibility' => 'public',
],
'myftpsite' => [
'driver' => 'ftp',
'host' => 'myhost',
'username' => 'ftpuser,
'password' => 'ftppwd',
// Optional FTP Settings...
// 'port' => 21,
'root' => '/WRK/FILE/TEST',
// 'passive' => true,
// 'ssl' => true,
// 'timeout' => 30,
],
In the Controller I store the file with:
... validation here ...
$path = $request->uploadfile->storeAs('', $request->uploadfile->getClientOriginalName(), self::STORAGEDISK);
$file = new TESTFile;
... db code here ...
$file->save();
At this point I would like to retrive the variable to pass to the download methods (url or path of my file). I found 2 ways
Storage::url($pspfile->filename) *return* **/storage/** accept.png
Storage::disk(self::STORAGEDISK)->getDriver()->getAdapter()->applyPathPrefix($pspfile->filename) *return* C:\xampp\htdocs\myLaravel\ **storage** \app\accept.png
Any help or suggestion to do it in a better way will be very appreciated.
EDIT
For the moment I separete local/public from FTP.
The download is working if in the Controller I modify
$path = $request->uploadfile->storeAs('',
$request->uploadfile->getClientOriginalName()
,self::STORAGEDISK);
$file->fullpath = $path;
with
$file->fullpath = storage_path('app\\') . $path;
where 'app\' is the storage_path configured as root in filesystem.php
Moreover I can avoid to hardcode and use
$file->fullpath = Storage::disk(self::STORAGEDISK)
->getDriver()
->getAdapter()
->getPathPrefix() . $path;
In this way the download method can use
return response()->download($pspfile->fullpath);
I am still looking for a way to retrive a valid scr attribute for an img tag.
In addition I would like the same with remote stored files (maybe with local temp dir and file?)
I made something similar some time ago. Maybe this example code helps you.
class FileController extends Controller
{
// ... other functions ...
public function download(File $file)
{
if (Storage::disk('public')->exists($file->path)) {
return response()->download(public_path('storage/' . $file->path), $file->name);
} else {
return back();
}
}
public function upload()
{
$this->validate(request(), [
'file-upload' => 'required|file',
]);
$path = request()->file('file-upload')->store('uploads', 'public');
$file = new File;
$file->name = request()->file('file-upload')->getClientOriginalName();
$file->path = $path;
$file->save();
return back();
}
}

Using and Configuring Zend Session and Zend Cache Memcached - Zend Framework 2.3

Actually, I'm using "standard" sessions manager config:
http://framework.zend.com/manual/current/en/modules/zend.session.manager.html
I want to use cache and save my session's data into server's cache (memcached) for improves performances and scalability.
I set php.ini like this (localhost memcached):
session.save_handler=memcached
session.save_path= "tcp://127.0.0.1"
and it show this error:
Warning: session_start(): Cannot find save handler 'memcached' - session startup failed in C:\Program Files (x86)\xampp\htdocs\Zend-application\vendor\zendframework\zendframework\library\Zend\Session\SessionManager.php on line 98
So, I don't understand how to configure my config/autoload/global.php and module/application/module.php. it's my first time that I want to implement memcached and caching in general. thanks, so much!
I tried to modify module/application/module.php like this:
---add session and cache ---
use Zend\Session\Config\SessionConfig;
use Zend\Session\Container;
use Zend\Cache\StorageFactory;
use Zend\Session\SaveHandler\Cache;
use Zend\Session\SessionManager;
use Zend\Session\Validator\HttpUserAgent;
use Zend\Session\Validator\RemoteAddr;
--- end session and cache ---
public function onBootstrap($e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$this->initSession(array(
'remember_me_seconds' => 180,
'use_cookies' => true,
'cookie_httponly' => true,
'validators' => array(
'Zend\Session\Validator\RemoteAddr',
'Zend\Session\Validator\HttpUserAgent',
'phpSaveHandler' => 'memcached',
'savePath' => 'tcp://127.0.0.1',
)
));
}
public function initSession($config)
{
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->getValidatorChain()
->attach(
'session.validate',
array(new HttpUserAgent(), 'isValid')
)
->attach(
'session.validate',
array(new RemoteAddr(), 'isValid')
);
$cache = StorageFactory::factory(array(
'adapter' => array(
'name' => 'memcached',
'options' => array(
'server' => '127.0.0.1',
),
)
));
$saveHandler = new Cache($cache);
$sessionManager->setSaveHandler($saveHandler);
$sessionManager->start();
Container::setDefaultManager($sessionManager);
}
but it shows this error:
Warning: ini_set() expects parameter 2 to be string, array given in C:\Program Files (x86)\xampp\htdocs\Zend-application\vendor\zendframework\zendframework\library\Zend\Session\Config\SessionConfig.php on line 88
Fatal error: Call to undefined method Zend\Stdlib\CallbackHandler::attach() in C:\Program Files (x86)\xampp\htdocs\Zend-application\module\Application\Module.php on line 68
this is my config/autoload/global.php
return array(
'db' => array(
'driver' => 'Pdo_Mysql',
'charset' => 'utf-8',
'dsn' => 'mysql:dbname=mydb;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
'session' => array(
'config' => array(
'class' => 'Zend\Session\Config\SessionConfig',
'options' => array(
'name' => 'zend-application',
),
),
'storage' => 'Zend\Session\Storage\SessionArrayStorage',
'validators' => array(
'Zend\Session\Validator\RemoteAddr',
'Zend\Session\Validator\HttpUserAgent',
),
),
);
Hoping it'll help someone, I resolved my issue. I'm working in Win7 enviroment and memcached doesn't work on it! I changed :
session.save_handler=memcached
session.save_path= "tcp://127.0.0.1"
to
session.save_handler=memcache
session.save_path= "tcp://127.0.0.1:11211"
I restored the "standard" session manager config and memcache works correctly. When I'll transfer the entire site to apache server, I'll change php.ini for using memcached.
http://framework.zend.com/manual/current/en/modules/zend.session.manager.html

Resources