I am trying to implement Redis publishing in my local RESTful API which is built in Laravel for the purposes of implementing a chat system later on with Web Sockets. I intend to read them from a Node.JS server later on.
I am using Redis::publish to publish a simple message to my test-channel.
However, for some reason Laravel doesn't seem to publish to it.
I have also noticed that when I call Redis::set, whatever I set doesn't get persisted in Redis, but using Redis::get I can read the values that I'm setting.
public function redis(Request $request) {
$data = $request->validate([
'message' => 'string|required'
]);
Redis::publish('test-channel', 'a test message');
return 'Done';
}
I am using the code above in the api/redis route:
Route::post('/redis', 'API\MessageController#redis');
I have subscribed to the test-channel using the redis-cli command.
If I manually publish a message to the test-channel using the redis-cli in a terminal instance, I properly receive the messages that I am publishing. However, they don't seem to get published with Laravel for some reason.
What I can notice while running php artisan serve and visiting the aforementioned route is Laravel logging the following:
[*timestamp*] 127.0.0.1:39448 Accepted
[*timestamp*] 127.0.0.1:39448 Closing
The port after 127.0.0.1 appears to be random.
I tried both php-redis php extension and the predis package, just to be sure that it isn't any one of them, but I get the same result with both of them. I am currently using php-redis with both igbinary and redis extensions enabled in /etc/php/config.d and have removed the Redis alias from config/app.php.
I am using PHP 7.4, Laravel 6.0 and Redis 5.0.7 on Manjaro.
Been there, discovered that with:
$ redis-client
psubscribe *
will show you what's going on.
Chances are that your default config/database.php contains something like:
'redis' => [
'client' => env('REDIS_CLIENT', 'predis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
In that case, the channel name will be prefixed with this prefix option.
So you can just comment this option, or, if you keep it, be sure to subscribe to the right channel
Redis::publish('test-channel', 'a test message');
$prefix = config('database.redis.options.prefix');
$channel = $prefix . 'test-channel';
return "Done. (published on $channel)";
Related
I'm working on a Laravel project and I want to use Redis to store session data for improved performance. I have set up Redis correctly and it's working fine with basic functionality. However, I'm having trouble getting the auth::attempt function to work with Redis.
Here's my current auth::attempt code:
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// User authentication successful
} else {
// User authentication failed
}
This works fine with the default session driver in Laravel, but I want to use Redis for better performance. I have tried changing the SESSION_DRIVER variable in my .env file to 'redis' and set the Redis connection in config/database.php, but I'm still getting an authentication error.
I'm not sure what I'm missing. Can anyone help me understand how to use Redis with auth::attempt in Laravel? Thanks in advance!
When using Redis for session storage in Laravel, you need to ensure that your Redis server is running and that your Laravel application is configured to use Redis as the session driver.
To set Redis as your session driver, you can change the value of the SESSION_DRIVER variable in your .env file to redis. You can also configure the Redis connection in the config/database.php file. Here's an example configuration:
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'table' => 'sessions',
'expire_on_close' => false,
],
Once you've configured Redis as your session driver, you can use the Auth::attempt method as usual. However, if you're still encountering authentication errors, there are a few things you can try:
Make sure your Redis server is running and accessible from your
Laravel application.
Check your Redis configuration in the config/database.php file to
ensure that it's set up correctly.
Clear your Laravel application's cache using the php artisan
cache:clear command.
Check your Redis server's logs for any errors or issues that might
be causing the authentication failures.
I recently added laravel/nexmo-notification-channel to my laravel project which also installed Nexmo/nexmo-laravel.
After installing, I published vendor files so that I get config/nexmo.php and in there I noted that it looks in the .env file for NEXMO_KEY and NEXMO_SECRET.
So I went ahead and created these within my .env file
NEXMO_KEY=[my_key]
NEXMO_SECRET=[my secret]
NEXMO_SIGNATURE_SECRET=[my signature secret]
After this, I added Nexmo to my service providers in app.php:
'providers' => [
...,
Nexmo\Laravel\NexmoServiceProvider::class
]
and also added the following in config/services.php:
'nexmo' => [
'key' => env('NEXMO_KEY', ''),
'secret' => env('NEXMO_SECRET', ''),
'sms_from' => '[my number]'
],
But I still get the following error when thrying to send an SMS using the use Illuminate\Notifications\Messages\NexmoMessage; class:
"message": "Provide either nexmo.api_secret or nexmo.signature_secret",
I can use these same credentials to send an SMS from CLI, so why can't I send it from laravel?
There have been a couple of workarounds for this that are valid, but at first glance it looks like the Nexmo package does the work to bring in the ENV secrets into Laravel's config. Because of caching problems, you should never call env() within Laravel, instead you should be using config() - so in this case, config(nexmo.api_secret).
My main point here though is that I can't look into the "correct" solution for you because the package is abandoned. Nexmo is no longer Nexmo, it's Vonage, and Laravel core team have subsequently updated the notification-channel package.
For supported use to integrate Vonage services (SMS), please use the following package:
https://github.com/laravel/vonage-notification-channel
I'm not sure exactly why, but, Vonage/Nexmo doesn't pick details from the .ENV.
Instead, use a global constant to fetch the secrets:
Create a global.php file in the config folder, and add your secrets from the env like this:
<?php
return [
// Other constants values
'SMS_API_KEY' => env('SMS_API_KEY', ''),
'SMS_API_SECRET' => env('SMS_API_SECRET', ''),
]
?>
Then, you can use the constants in your controller as usual:
'key' => config('global.SMS_API_KEY'),
'secret' => config('global.SMS_API_SECRET')
then: recache, php artisan config:cache
I'm trying to set up Chrome Logger to use alongside Laravel as detailed in "Easy Laravel 5", however following the instructions throws errors, and I'm new to Laravel (and not very experienced in PHP), so I'm not sure how to resolve them. We are directed to add a piece of code to the bootstrap/app.php file to use the chrome logger in the book.
The following is a screenshot of the error screen:
The following is the site without the code excerpt:
I tried requiring the chrome.php file using require_once() in the app.php file, but the error still persists. Removing the code excerpt produces the default screen.
This is the code excerpt:
if ($app->environment('local'))
{
$app->configureMonologUsing(function($monolog)
{
$monolog->pushHandler(new \Monolog\Handler\ChromePHPHandler());
});
}
I expected to be able to use the chrome logger, but instead receive the aforementioned error screen.
Add new channel in your configuration file (config/logging.php):
'chrome' => [
'driver' => 'monolog',
'handler' => \Monolog\Handler\ChromePHPHandler::class,
'formatter' => \Monolog\Formatter\ChromePHPFormatter::class
]
Sometimes you may wish to log a message to a channel other than your application's default channel. You may use the channel method on the Log facade to retrieve and log to any channel defined in your configuration file:
Log::channel('chrome')->info('Something happened!');
If you would like to create an on-demand logging stack consisting of multiple channels, you may use the stack method:
Log::stack(['single', 'chrome'])->info('Something happened!');
You can set new channel by default in your .env file
LOG_CHANNEL=chrome
or you can set
LOG_CHANNEL=stack
and change 'stack' list of channels (config/logging.php) like this:
'stack' => [
'driver' => 'stack',
'channels' => ['single', 'chrome'],
'ignore_exceptions' => false
]
After you can use log with all your list of channels
Log::info('General information log');
From Laravel 5.6 documentation.
The configureMonologUsing Method
If you were using the configureMonologUsing method to customize the
Monolog instance for your application, you should now create a custom
Log channel. For more information on how to create custom channels,
check out the full logging documentation.
Looks like we need to be on the earlier version for this to work.
i am working on Redis to store data Everything is working fine in my local system. i have successfully installed redis also in laravel with this command composer require predis/predis also and Redis setup of window also installed. Now when i store data in Redis like this:-
Redis::set('first',"My first Test"); // put data in Redis key
echo Redis ::get('first'); // get data
Above code is working fine in my local system. when i try to use this code in live server it is showing the below error:-
Please help me to resolve this issue. We are using amazon-ec2 server Thanks in advance :)
I had the same issue. But I believe its related to php 7 rather than Larevel 5.4 because I'm using Laravel 5.1 and I still have the problem.
I came across 2 solutions
Use use Illuminate\Support\Facades\Redis; instead of use Redis; if you want to call the Redis methods statically.
Change to dynamic calling
$redis = new Redis();
$redis->set('boo','Have beer and relax!')
$redis->get('boo');
Just remove or comment out extension=php_redis.dll from your php.ini
Laravel and server Redis conflicts with name "Redis"
This will work
In Laravel database config you can define a client for your Redis handler.
As you have installed predis, your Redis database configuration should look like this
'redis' => [
'client' => 'predis',
'cluster' => false,
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
PhpRedis extension and Laravel alias for Redis Facades are same which is creating the issue. In case you want to use the PhpRedis extension you need to change the alias keyword defined in app.php and client in the database config.
I am trying to configure cakephp ver 2.6.0 to use redis engine by default. but somehow i am not able to make it work. any help will be highly appreciated.
Things Which i have tried so far..
Configured app/config folder 2 files , core.php and bootstrap.php. , according to the guidelines provided here in this blog configure cake with redis and this blog too Another cake-redis config setup
but i keep on getting errors like.
Fatal error: Uncaught exception 'CacheException' with message 'Cache engine session is not properly configured.' in C:\wamp\www\project\cakephp\cakephp_2.6.0\lib\Cake\Cache\Cache.php on line 181
CacheException: Cache engine session is not properly configured. in C:\wamp\www\project\cakephp\cakephp_2.6.0\lib\Cake\Cache\Cache.php on line 181
Any help will be highly appreciated.
I was having the same exact issue today while trying to setup CakePHP to use Redis as the cache engine.
Coincidentally, I also read the same setup instructions from the two blogs you linked to.
The reason was that I had copied pasted the Configure::write(...) code block from the Another cake-redis config setup blog post as it is and pasted it into the file without first commenting out the Configure::write(...) code block that was already in the core.php file.
I'm assuming that you have already successfully setup Redis on Windows and have installed the PHPRedis extension without any issues.
I am using the instructions from Another cake-redis config setup here.
In your app/Config/core.php file, comment out the following block: (this was starting at line 218 in my core.php)
Configure::write('Session', array(
'defaults' => 'php'
));
Instead, you can put this in: (You can change the values to suit your particular needs)
Configure::write('Session', array(
'defaults' => 'cache',
'timeout' => 100,
'start' => true,
'checkAgent' => false,
'handler' => array(
'config' => 'session'
)
));
After this, change the value of $engine to 'Redis', so it becomes:
$engine = 'Redis';
And then, put this code in, I put this in at the very end of the file: (Again, your values can be different depending on what your setup is)
Cache::config ('session', array (
'Engine' => $engine,
'Prefix' => $prefix . 'cake_session_',
'Duration' => $duration
));
And that's it. You're done! No need to change anything else.
To make sure that Redis is working properly with CakePHP, I ran the RedisEngine Test Suite that comes with CakePHP. You need to have PHPUnit installed for this to work.
It can be accessed via http://your-cakephp-project/test.php
Click on 'Tests' under Core and then click on 'Cache/Engine/RedisEngine'
If everything is working successfully, you should see all the tests pass.
Alternatively, you can use redis-cli at the command prompt to confirm that Redis is storing keys properly.
Once you have logged in by typing redis-cli, type KEYS *
This should give you a list of keys related to your CakePHP setup.
An example would be the "myapp_cake_core_object_map" key.
Hope this helps.