Laravel 4 : Call to undefined method Redis::connection() - laravel

I'm going crazy about this error.
I've got a vagrant VM with Debian 7, generated with Puphpet, installation was fine.
1. Redis is installed and working
redis-server is running :
I can use the server on 127.0.0.1:6379 :
2. php5-redis is installed
php5-redis is actually installed :
3. Laravel Redis config is set
Here is my redis config file in app/local/database.php :
'redis' => [
'cluster' => false,
'default' => [
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
],
],
4. The call to Redis is simple :
// Get redis
$redis = Redis::connection();
5. I tried a lot of things
sudo service nginx reload
sudo service redis-server force-reload
composer dumpautoload
But nothing solved the error.
I'm still having :
ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method Redis::connection()' in /var/www/fd/app/menus/admin.menu.php:16
(line 16 is where I do the connection $redis = Redis::connection();)
Where am I wrong ?
Btw, I hate mondays >.>

I came across this after encountering this issue and wanted to add another answer in case it helps someone else.
In my case there was an alias collision because my php configuration has the PHP-Redis module/extension enabled -- both the PHP module and Laravel seem to have a conflicting object named Redis. I was able to resolve this simply by using the entire namespaced identifier:
//$r = Redis::connection()
$r = Illuminate\Support\Facades\Redis::connection();

The problem isn't with your redis server setup -- there's something mis-configured or changed in your system.
The error you're seeing
Call to undefined method Redis::connection()
Is PHP telling you it can't find a method named connection on the class Redis. It's a PHP error, and PHP never gets around to trying to talk to the redis server.
Normally, in a Laravel 4.2 system, there is no class named Redis. Instead, an alias is setup in app/config/app.php
#File: app/config/app.php
'Redis' => 'Illuminate\Support\Facades\Redis',
which turns Redis into a facade. This is what enables you to make calls like Redis::connection.
So, there's something wrong with your system. Either you
Have a custom class named Redis somewhere that's loaded before the aliases are setup
Have Redis aliased to something other than a the Illuminate\Support\Facades\Redis facade class
You Redis facade class has been modified to return a service identifier other than redis
You've rebound the redis service as some other class
Per the comments below, you have the Redis PHP extension installed and the global extension class "wins"
To find out where PHP thinks the Redis class is, try
$r = new ReflectionClass('Redis');
var_dump($r->getClassFile());
To see if #4 is the problem, try calling the service directly
$app = app();
$app['redis']->connection();
Good luck!

That error is because you have installed and enabled the module php5-redis, it became with the class Redis. To avoid that error and use the Laravel Redis Facade, you have to change the alias in app/config/app.php (or whatever is your environment).
'Redis' => 'Illuminate\Support\Facades\Redis'
'RedisFacade' => 'Illuminate\Support\Facades\Redis' //whatever you like
or just configure your cache.php to use Redis and use only the Cache class. :)

Install Redis extension on your PC.
Download the CORRECT version the DDL from the following link:
https://pecl.php.net/package/redis/4.1.0/windows
Put the dll in the correct folder
Wamp -> C:\wamp\bin\php\php-XXXX\ext
Laragon -> C:\laragon\bin\php\php-XXX\ext
Edit the php.ini file adding
extension=php_redis.dll
Restart server and check phpinfo();. Now Redis should be there!

Related

CodeIgniter 4 plus Myth/Auth throws error when running Migrations via php spark migrate -all

I have discovered some wired behavior, I have that one CI4 project i am working on since a couple of weeks. everything is working just fine, but until now i have just been working with the project on my local machine. When i wanted to run the project on my Laptop in ran into an error when i tried to run the migrations with php spark migrate -all
CodeIgniter CLI Tool - Version 4.0.4 - Server-Time: 2020-07-20 06:16:02am
Running all new migrations...
An uncaught Exception was encountered
Type:        CodeIgniter\Database\Exceptions\DatabaseException
Message:     Unable to connect to the database.
Filename:    /opt/lampp/htdocs/sms/vendor/codeigniter4/framework/system/Database/BaseConnection.php
Line Number: 425
The project includes Myth/auth, so i tried just to run "my" migration with php spark migrate . That just worked fine, no problem at all, the tables are there, no errors. Just for fun, i moved my Math/auth migrations from the vendor folder to the "normal" Database/Migrations folder and was able to migrate them that way.
That's very wired, especially since everything is working just fine on the PC I have been using before. There I am able to run the migrations using php spark migrate -all without any errors, when is set up a fresh MySQL/MariahDB database. But somehow only there.
I was able to reproduce the error on my laptop on my Manjaro partition, my Windows 10 partition and on my iMac.
So if you want to reproduce the error do the following:
composer create-project codeigniter4/appstarter whatever
rename the env to .env
set CI_ENVIRONMENT = development and obviously uncomment that line
configure and uncomment your database setting in the .env
create a sample migration like the one from the docs using > php spark migrate:create AddBlog
add the following content to the new migration and save the file:
forge->addField([
'blog_id' => [
'type' => 'INT',
'constraint' => 5,
'unsigned' => true,
'auto_increment' => true,
],
'blog_title' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
'blog_description' => [
'type' => 'TEXT',
'null' => true,
],
]);
$this->forge->addKey('blog_id', true);
$this->forge->createTable('blog');
}
public function down()
{
$this->forge->dropTable('blog');
}
}
run > composer require myth/auth
Edit app/Config/Email.php and verify that a fromName and fromEmail are set as that is used when sending emails for password reset, etc.
Edit app/Config/Validation.php and add the following value to the ruleSets array: \Myth\Auth\Authentication\Passwords\ValidationRules::class
Ensure your database is setup correctly, then run the Auth migrations: php spark migrate -all
As a result you will also have the above error. I was not able to
get around that error, except for the system in was working with at
first.
If you just use php spark migrate it will migrate the sample migration without any errors
I am running CI 4.04 on Kubuntu 18.04 LTS, running apache2.4.29 and PHP 7.4.9
The short answer is...
Using php spark migrate -all searches everywhere it knows about for Database/Migrations Folders and files.
There just so happens to be a such folder/file under
tests/_support/Database/Migrations/2020-02-22-222222_example_migration.php
The bits added to make the short answer longer
So the Database error we are seeing is due to not having set up Database credentials for $tests in /app/Config/Database.php
All it's doing is looking to connect to the DB set up under $tests, but appears not to actually run as we don't want it to.
That appears to be enabled when ENVIRONMENT is set to "testing".
So 3 options for the time being...
Ignore the error. But that always leaves you wondering what's really happening.
Setup the credentials for the $tests Database. (Not really warranted.) OR
Delete/Rename the tests folder if you are not using it. (Stop it finding it.)
Would be to use the -n switch/option and specify the namespace to use (but not sure that's working.)
Changing DB hostname to '127.0.0.1' from localhost in your .env file usually solves the problem of running any migrations from the command line.
Open your PHP.ini file, find this :
;extension=sqlite3
and remove the semicolon to activate sqlite3. You need this library in Codeigniter 4 in order to use FORGE.

Getting a 'Please make sure the PHP Redis extension is installed and enabled.' error despite the extension being loaded

I'm getting spammed with Please make sure the PHP Redis extension is installed and enabled. in my logs, despite having the redis.so extension installed on MacOS. I installed the Redis extension by running pecl install redis, which succeeds with the following message:
Installing '/usr/local/Cellar/php/7.3.12/pecl/20180731/redis.so'
install ok: channel://pecl.php.net/redis-5.1.1
Extension redis enabled in php.ini
By running phpinfo() in tinker, I can see that my loaded php.ini is
Configuration File (php.ini) Path => /usr/local/etc/php/7.3
Loaded Configuration File => /usr/local/etc/php/7.3/php.ini
If I open up /usr/local/etc/php/7.3/php.ini, extension="redis.so" is listed at the top of the file.
What makes this more and more strange is that if I dig deeper into where the original Please make sure the PHP Redis extension is installed and enabled. error is coming from, it looks to be in laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php:76, which looks like this:
throw new LogicException(extension_loaded('redis') ? 'Please remove or rename the Redis facade alias in your "app" configuration file in order to avoid collision with the PHP Redis extension.' : 'Please make sure the PHP Redis extension is installed and enabled.');
So according to this, the extension isn't loaded. But if I load up tinker again and run extension_loaded('redis') then I get a true result.
I can't for the life of me figure out what's going on here. Why does PhpRedisConnector not see that the extension is loaded?
For completeness, I've also removed the Redis alias from my app.php file as instructed to by the Laravel docs.
For those who installed Redis with composer require predis/predis, as described in the Laravel official documentation.
In config/database.php, change:
'redis' => [
//'client' => env('REDIS_CLIENT', 'phpredis'),
'client' => env('REDIS_CLIENT', 'predis'),
The accepted answer is just a workaround to use predis instead of PHPRedis. If you still want to use PHPRedis and still facing the same issue as the main question then maybe you are running into the same issue as me. In my case the Please make sure the PHP Redis extension is installed and enabled error only throw out if running the Job by crontab. Turn out that somehow the version of PHP which using in the crontab is not the same as the PHP version that I installed the PHP Redis to. So here is what I did:
Find out where is the current PHP path:
MacBook-Pro:hpt hantran$ which php
/usr/local/bin/php
Change the crontab from
* * * * * cd /Applications/XAMPP/xamppfiles/htdocs/hpt && php artisan schedule:run >> /dev/null 2>&1
To:
* * * * * cd /Applications/XAMPP/xamppfiles/htdocs/hpt && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1
The original answer can be found here https://laracasts.com/discuss/channels/general-discussion/please-make-sure-the-php-redis-extension-is-installed-and-enabled?page=1#reply=659249
Add this to your env file
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_CLIENT=predis <---Add this line-->

How to fix "Non-static method Spatie\Analytics\Analytics::fetchVisitorsAndPageViews() should not be called statically?"

When i put:
use Spatie\Analytics\Analytics;
It gives the error
'Non-static method should not be called statically'
But when I only put:
use Analytics;
I gives a white page on refresh or says
"The use statement with non-compound name 'Analytics' has no effect "
when starting.
I am using Laravel 5.5.4 and although it says the facade should be automatically setup, it wasn't working so I also added this manually to the // config/app.php:
'Analytics' => Spatie\Analytics\AnalyticsFacade::class,
But it still is not working.
from the package github. there was a solution
php artisan config:clear
but it did not work for me.
This package can be installed through Composer.
composer require spatie/laravel-analytics
In Laravel 5.5 and above the package will autoregister the service provider. In Laravel 5.4 you must install this service provider.
config/app.php
'providers' => [
...
Spatie\Analytics\AnalyticsServiceProvider::class,
...
];
In Laravel 5.5 and above the package will autoregister the facade. In Laravel 5.4 you must install the facade manually.
config/app.php
'aliases' => [
...
'Analytics' => Spatie\Analytics\AnalyticsFacade::class,
...
];
You want to use the facade to access the class, you will need to change:
use Spatie\Analytics\Analytics; to use Analytics;
Another way around just import this to your class:
use Spatie\Analytics\AnalyticsFacade as Analytics
It depends in what context you place the use statement.
In Laravel you also can use facades without having to import it with use.
The same class can be called by using \Analytics in your code call.
Example:
\Analytics::fetchMostVisitedPages(\Period::days(7));

Why Laravel uses wrong database file after setting environment?

In bootstrap/start.php I have the following:
$env = $app->detectEnvironment(function()
{
if($myenv = getenv('APPLICATION_ENV')):
return $myenv;
else:
return 'local';
endif;
});
Ok so I setup a local folder and put in a database.php file with my local connections.
Just to make sure its picking up the correct environment I put in the template: {{ App::environment(); }} which outputs local.
But when making a DB call its giving me error: Undefined index: DB1_HOST
My base (production) database.php file has:
'host' => $_SERVER["DB1_HOST"],
'database' => $_SERVER["DB1_NAME"],
'username' => $_SERVER["DB1_USER"],
'password' => $_SERVER["DB1_PASS"],
Why is it looking at the production database file?
Laravel also stores the config information in
bootstrap/cache/config.php
In some cases it's not updated which may result in wrong database information. Deleting the file should resolve the issue.
If you are trying to use artisan in your terminal and you want to set the environment variable once and for all, you can do :
export APPLICATION_ENV=local
And check you current environment using php artisan env
Production config files are loaded first and then merged with overrides from other environments. If the production file generates an error (e.g. undefined index) the config loading will bail early without loading the overrides. In the production config file, check the value is set before attempting to use it and the local config file will then load correctly.
Clean the config cache as it may affect
php artisan config:cache

Laravel Facade not being loaded

I started with a fresh installation of Laravel and then did the following...
I filled in the config/workbench.php file with my info: -
return array('name' => 'My Name', 'email' => 'fullysick#email.com');
I ran the artisan command: -
php artisan workbench dicksmith/curl --resources
Everything reported success. It installed dependencies etc.
I populated the app.php file with the necessary service provider and alias information. My code can be seen here -> http://paste.laravel.com/wFj
I'm struggling to think why it may not be loading through the Facade accessor.
Any ideas?
Problem solved.
I just needed to have the Facades directory located inside the package.
A stupid, stupid, stupid, stupid mistake on my behalf. 2 days lost... I feel sheepish.

Resources