Laravel broadcasting channel function won't fire - php

So I'm gonna use laravel broadcasting for a chat app,
I followed Laravel Broadcasting approach,
Uncommented App\Providers\BroadcastServiceProvider
from providers array inside config/app.php
Registered in pusher website, made a channel
and filled the fields below inside .env file with my pusher channel info
PUSHER_APP_ID
PUSHER_APP_KEY
PUSHER_APP_SECRET
PUSHER_APP_CLUSTER
Inside my broadcast.php config file where I set the default driver to pusher, I also added
'options' => [
'cluster' => 'us2',
'encrypted' => true,
],
to pusher array inside connections array based on my channel info in pusher panel
Installed pusher php package on my laravel project using composer require pusher/pusher-php-server "~3.0" command
Here is my event class
<?php
namespace App\Events;
use App\User;
use App\TherapyMessage;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\AppLog;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
class TherapyMessageSent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* User that sent the message
*
* #var User
*/
public $user;
/**
* Message details
*
* #var Message
*/
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(User $user, TherapyMessage $message)
{
$this->user = $user;
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
$message_id = $this->message->id;
$user = $this->user;
AppLog::create([
'file_name' => __FILE__,
'message' => "broadcast before send with Message ID of $message_id from $user->full_name"
]);
return new PrivateChannel("therapy-chat.$message_id");
}
}
The AppLog is a model that I use for logging inside the project
I tried implementing ShouldBroadcast interface at first but that didn't work either
I also registered my event inside EventServiceProvider.php file and run php artisan event:generate command, here is the EventServiceProvider $listen array:
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
TherapyMessageSent::class
],
];
I also imported the event namespace next to other namespaces inside the file:
use \App\Events\TherapyMessageSent;
Here is the channel that I defined inside routes/channels.php file:
use App\AppLog;
Broadcast::channel('therapy-chat.{message_id}', function ($user, $message_id) {
AppLog::create([
'file_name' => __FILE__,
'message' => "broadcast sending with Message ID of $message_id to $user->full_name"
]);
if (!Auth::check()) return false;
$message = \App\TherapyMessage::find($message_id);
if (!$message) {
AppLog::create([
'file_name' => __FILE__,
'message' => "Message with ID of $message_id Not Found for broadcasting"
]);
return false;
}
$will_send = false;
if ($therapist = $user->therapist) {
$will_send = $therapist->id === $message->therapist_id;
} else if ($patient = $user->patient) {
$will_send = $message->patient_id === $patient->id;
}
if ($will_send) {
AppLog::create([
'file_name' => __FILE__,
'message' => "Message with ID of $message_id broadcasted to $user->full_name"
]);
}
return $will_send;
});
Finally, this is my controller method:
public function sendToTherapist(Request $request) {
$validation = \Validator::make($request->all(), ['message' => 'required']);
if ($validation->fails()) return $this->validationError($validation);
$user = \Auth::user();
$patient = $user->patient;
$therapist = $patient->therapist;
if (!$therapist) return $this->errorWithMessage('Patient does not have Therapist');
$message = \App\TherapyMessage::create([
'patient_id' => $patient->id,
'therapist_id' => $therapist->id,
'type' => TherapyMessageType::TEXT,
'text' => $request->message,
'sender_role' => TherapyMessageSenderRole::PATIENT
]);
broadcast(new TherapyMessageSent($user, $message))->toOthers();
return $this->success(['id' => $message->id]);
}
My controller class extends from BaseController which is a custom controller class with helper methods such as success(), validationError() and errorWithMessage()
As you see in the code above
I filled $user and $message with correct values and the request works without any error
I think the channel method won't even be fired,
as I check the AppLog table when I call broadcast method, only the log inside TherapyMessageSent event broadcastOn function is saved
and even the log that I save at the beginning of channels.php method, isn't saved so I think this method is never executed.
If anyone could help me with the problem, I'd be thankful.

Related

Laravel Websocket package issue with the latest Laravel, pusher, and Echo package

I am working on Laravel 9 where I install Laravel WebSocket, Laravel Echo, and Pusher PHP server.
By the way, I didn't use the official Pusher application, just using the package as per Laravel-WebSocket package documentation suggested.
User case - I want to update the site model value and send a notification (broadcast and mail) to the end user as soon as the user deletes a site.
Everything is installed and working fine but I found some glitches in the Laravel-WebSocket, Pusher package.
I have created the following event which will broadcast to the end user.
SiteDelete.php
<?php
namespace App\Events;
use App\Models\Site;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class SiteDeleted implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* The site instance.
*
* #var \App\Models\Site
*/
public $site;
/**
* The name of the queue connection to use when broadcasting the event.
*
* #var string
*/
public $connection = 'database';
/**
* The name of the queue on which to place the broadcasting job.
*
* #var string
*/
public $queue = 'default';
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Site $site)
{
$this->site = $site;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
// return new PrivateChannel('site.delete.'.$this->site->id); // this is not working.
// return [new PrivateChannel('site.delete.'.$this->site->id)]; // this is not working.
return [new PrivateChannel('site.delete.'.$this->site->id), new Channel('mock')]; // This will call but I need to pass two channels intentionally.
}
/**
* Get the data to broadcast.
*
* #return array
*/
public function broadcastWith()
{
return ['id' => $this->site->id];
}
}
app.js
Echo.private("site.delete.1")
.listen('SiteDeleted', (e) => {
console.log("SiteDeleted");
console.log(JSON.stringify(e));
})
Echo.private('App.Models.User.7')
.notification((notification) => {
console.log("App.Models.User");
console.log(notification);
});
Problem
As you can see comments in my event class's broadcastOn method where I need to pass two channels. One is real and the second one is fake. So ultimately you need to pass at least two channels so the pusher request will have a channels parameter [which will work] but the channel parameter never works[i.e when you pass a single channel].
I can able to send custom events from the WebSocket GUI. i.e from http://localhost:8000/laravel-websockets URL. but those events are never caught by the front end unless I do it the dirty way.
The notifications are never caught by the front end due to this channel and channels parameter issue.
Dirty Way[Yes I know we should never touch the vendor folder but just curious to know why the things are not working]
I checked the vendor folder very deeply and I come to know, in the vendor/pusher/pusher-php-server/src/Pusher.php under the make_event function if I update the following line then it starts working without passing two channels.
vendor/pusher/pusher-php-server/src/Pusher.php
private function make_event(array $channels, string $event, $data, array $params = [], ?string $info = null, bool $already_encoded = false): array
{
// if (count($channel_values) == 1) {
// $post_params['channel'] = $channel_values[0];
// } else {
// $post_params['channels'] = $channel_values;
// }
$post_params['channels'] = $channel_values;
}
My Research
As the WebSocket package suggests installing pusher-php-server version 3.0 but I install the latest one i.e 7. Version 3.0 is incompatible with Laravel 9. But I can't and don't want to install the older version.
I think the WebSocket package is not able to send the event and data on a single channel with a newer version of pusher-php-server.
I can't raise an issue (or blame it) for Pusher SDK because we are just replacing the package and I think the Pusher SDK package is working fine when you use their credentials(ie. you have to create an app on Pusher).
Even if you can check on the WebSocket dashboard i.e http://localhost:8000/laravel-websockets when you send the event it will never catch in the front end. But as soon as you update the Pusher.php file it starts catching an event on the front end.
due to the above reason, as you know the notification are sent to the user on their private channels, So I can't add a mock channel for notification as I did for my event, so notification will never catch by the frontend application.
composer.json
"beyondcode/laravel-websockets": "^1.13",
"pusher/pusher-php-server": "^7.2",
"laravel/framework": "^9.19",
package.json
"pusher-js": "^7.5.0",
"laravel-echo": "^1.14.2",
I tried the explicit way as well i.e using the pusher SDK's functions[which are giving 200 status code] but not working. As soon as I do it the dirty way it starts working, I mean everything starts working without any issue.
public function pusherTesting(Request $request)
{
$path = "/apps/123456/events";
$settings = [
'scheme' => 'http',
'port' => '6001',
'path' => '',
'timeout' => '30',
'auth_key' => '1b5d6e5b1ab73b',
'secret' => '3739db6a99c1ba',
'app_id' => '123456',
'base_path' => '/apps/123456',
'host' => '127.0.0.1',
];
$params = [];
$body = '{"name":"Illuminate\\Notifications\\Events\\BroadcastNotificationCreated","data":"{\"site_id\":1,\"domain_url\":\"yucentipede-tuvo.blr3.instawp-testing.xyz\",\"save\":\"socket\",\"id\":\"2f53aac0-8d83-45f4-962d-516c1c8bc97c\",\"type\":\"App\\\\Notifications\\\\SiteDeletedNotification\"}","channels":["private-App.Models.User.7"]}';
$params['body_md5'] = md5($body);
$params_with_signature = \Pusher\Pusher::build_auth_query_params(
$settings['auth_key'],
$settings['secret'],
'POST',
$path,
$params
);
$headers = [
'Content-Type' => 'application/json',
'X-Pusher-Library' => 'pusher-http-php 7.2.1'
];
$client = new \GuzzleHttp\Client();
try {
$response = $client->post(ltrim($path, '/'), [
'query' => $params_with_signature,
'body' => $body,
'http_errors' => false,
'headers' => $headers,
'base_uri' => 'http://127.0.0.1:6001'
]);
} catch (Exception $e) {
print_r($e->getMessage());
}
$response_body = json_decode($response->getBody(), false, 512, JSON_THROW_ON_ERROR);
echo $status = $response->getStatusCode();
die;
}

Laravel5.8 Pusher not working. Cannot receive

I am creating realtime chat app.
I have set up pusher in my laravel and vue.js project.
But it doesn't work. Though I don't have any error in the console.
Also, I have no error in network tab.
I need to create messenger app, so I need a realtime chat function.
Now, I can push user's comment but in the other user's window, nothing shows up.
But it does, once I refresh the page. I think my pusher setting has something wrong, because in the pusher debug console, any session is not executed.
Here is my code.
.env
BROADCAST_DRIVER=pusher
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
PUSHER_APP_ID=my id
PUSHER_APP_KEY=my app key
PUSHER_APP_SECRET= my secret key
PUSHER_APP_CLUSTER=mt1
broadcasting.php
'pusher' => [
'driver' => 'pusher',
'key' => env('my key'),
'secret' => env('my secret key'),
'app_id' => env('my id'),
'options' => [
'cluster' => 'ap3',
'encrypted' => true,
],
BroadcastServiceProvider.php
Broadcast::routes(['middleware' => ['auth:api']]);
require base_path('routes/channels.php');
bootstrap.js
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'my key',
cluster: 'ap3',
encrypted: true
});
NewMessage.php
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class NewMessage implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('messages.' . $this->message->to);
}
public function broadcastWith()
{
$this->message->load('fromContact');
return ["message" => $this->message];
}
}
routes/channel.php
use Illuminate\Support\Facades\Broadcast;
ContactsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Message;
class ContactsController extends Controller
{
public function get() {
$contacts = User::where('id', '!=', auth()->id())->get();//全部のcontactをjson経由でgetする
return response()->json($contacts);
}
public function getMessagesFor($id) {
$messages = Message::where('from', $id)->orWhere('to', $id)->get();
return response() -> json($messages);
}
public function send(Request $request) {
$message = Message::create([
'from' => auth()->id(),
'to' => $request->contact_id,
'text' => $request->text
]);
return response()->json($message);
}
}
Here is what I tried.
run all the command according to the laravel document.
php artisan chache:clear
and run the server again.
run php artisan queue:work
in command terminal
Did you write
window.Echo.private('channelName').listen('EventName',function(e){
})
in your application to listen
In your send() function you should write
broadcast(new NewMessage($message));
to broadcast the message.

Laravel: Actively listening events from external service

I'm developing a PBX monitoring app with Laravel. On PBX side, Asterisk is managing the calls.
I can use PAMI client to receive all events from Asterisk Manager Interface. If I simply run this script from console, all the events on Asterisk are printed on the screen in real time:
<?php
require __DIR__ . '/vendor/autoload.php';
use PAMI\Client\Impl\ClientImpl as PamiClient;
use PAMI\Message\Event\EventMessage;
use PAMI\Listener\IEventListener;
$pamiClientOptions = array(
'host' => '',
'scheme' => 'tcp://',
'port' => 5038,
'username' => '',
'secret' => '',
'connect_timeout' => 10000,
'read_timeout' => 10000
);
$pamiClient = new PamiClient($pamiClientOptions);
// Open the connection
$pamiClient->open();
$pamiClient->registerEventListener(function (EventMessage $event) {
var_dump($event);
});
$running = true;
// Main loop
while($running) {
$pamiClient->process();
usleep(1000);
}
// Close the connection
$pamiClient->close();
What I'm trying to do is implementing events&listeners in Laravel with PAMI. But it doesn't seem to work.
I have registered the event and listener on EventServiceProvider class:
protected $listen = [
'App\Events\AmiEventOccurred' => [
'App\Listeners\LogAmiEvent',
],
My event class:
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
class AmiEventOccurred
{
use Dispatchable, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct()
{
$pamiClientOptions = array(
'host' => getenv('PAMI_HOST'),
'scheme' => getenv('PAMI_SCHEME'),
'port' => getenv('PAMI_PORT'),
'username' => getenv('PAMI_USERNAME'),
'secret' => getenv('PAMI_SECRET'),
'connect_timeout' => getenv('PAMI_CONNECT_TIMEOUT'),
'read_timeout' => getenv('PAMI_READ_TIMEOUT'),
);
$pamiClient = new \PAMI\Client\Impl\ClientImpl($pamiClientOptions);
// Open the connection
$pamiClient->open();
$pamiClient->registerEventListener(function (\PAMI\Message\Event\EventMessage $message) {
$this->message = $message;
});
$running = true;
// Main loop
while($running) {
$pamiClient->process();
usleep(1000);
}
// Close the connection
$pamiClient->close();
}
}
My listener class:
<?php
namespace App\Listeners;
use App\Events\AmiEventOccurred;
class LogAmiEvent
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param AmiEventOccurred $event
* #return void
*/
public function handle(AmiEventOccurred $event)
{
Log::debug(print_r($event, true));
}
}
Is this a correct approach? Is it possible to actively listen to another service in real time with Laravel events, or should I develop another app for it to run in real time on the background and trigger Laravel events when necessary?
All of this code doesn't belong in an event. An event is just for announcing that something has happened, and containing all of the important information about what it was. Your code for running a client and sleeping and all of that should be somewhere else, likely an artisan command that your kernel keeps running. Then in that code, when something happens, you trigger a simple event with the message for any listeners to act on:
$pamiClient->registerEventListener(function (\PAMI\Message\Event\EventMessage $message) {
new AmiMessageReceived($message);
});

How to execute Zend Framework 3 action with zf-console?

I want to execute ZF3 action with zf-console.
I can do this using zend-mvc-console module and it works fine.
For example.
Application/config/module.config.php:
'console' => [
'router' => [
'routes' => [
'cronroute' => [
'options' => [
'route' => 'sync',
'defaults' => [
'controller' => Controller\ConsoleController::class,
'action' => 'syncEvents'
]
]
]
]
]
],
Application/src/Controller/ConsoleController.php
class ConsoleController extends AbstractActionController
{
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager
*/
private $entityManager;
/**
* User Manager
* #var Application\Service\UserManager
*/
private $userManager;
/**
* Constructor.
*/
public function __construct($entityManager, $userManager)
{
$this->entityManager = $entityManager;
$this->userManager = $userManager;
}
public function syncAction()
{
$response = $this->userManager->syncUserInfo();
return $response ? 'Sync Success' : 'Failed to sync';
}
}
But it says that it will be deprecated:
https://zendframework.github.io/zend-mvc-console/intro/#deprecated
It suggest to use zf-console from zfcampus:
https://github.com/zfcampus/zf-console
But I cannot find a way to execute Controller action or to use my build services (like UserManager).
There is example to build Zend Application and retrieve Service manager:
use Zend\Console\Console;
use Zend\Console\ColorInterface as Color;
use ZF\Console\Application;
use ZF\Console\Dispatcher;
chdir(dirname(__DIR__));
require __DIR__ . '/../vendor/autoload.php'; // Composer autoloader
$application = Zend\Mvc\Application::init(require 'config/application.config.php');
$services = $application->getServiceManager();
$buildModel = $services->get('My\BuildModel');
Is there a way to execute Controller action with it? Or Can I load my UserManager service?
I tried to get My UserManager:
$buildModel = $services->get('Application\Service\UserManager');
But receiving error:
PHP Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Unable to resolve service "Application\Service\UserManager" to a factory; are you certain you provided it during configuration?' in /var/www/html/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:687
The zend-mvc-console module does seem to be on the edge of deprecation. Just like you I was trying to implement zfcampus/zf-console. Since the mvc-console module seems to be (almost) deprecated, I suggest you use something different than (mvc) controllers for your console work. I used a class that can handle the call (in a way zf-console expects).
This is a dummy example I was working on for my project;
This is script that is called on the command line:
use Zend\Console\Console;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\Glob;
use ZF\Console\Application;
use ZF\Console\Dispatcher;
require_once __DIR__ . '/vendor/autoload.php'; // Composer autoloader
$configuration = [];
foreach (Glob::glob('config/{{*}}{{,*.local}}.php', Glob::GLOB_BRACE) as $file) {
$configuration = ArrayUtils::merge($configuration, include $file);
}
// Prepare the service manager
$smConfig = isset($config['service_manager']) ? $configuration['service_manager'] : [];
$smConfig = new \Zend\Mvc\Service\ServiceManagerConfig($smConfig);
$serviceManager = new ServiceManager();
$smConfig->configureServiceManager($serviceManager);
$serviceManager->setService('ApplicationConfig', $configuration);
// Load modules
$serviceManager->get('ModuleManager')->loadModules();
$routes = [
[
'name' => 'dumb',
'route' => '[--foo=]',
'description' => 'Some really cool feature',
'short_description' => 'Cool feature',
'options_descriptions' => [
'foo' => 'Lorem Ipsum',
],
'defaults' => [
'foo' => 'bar',
],
'handler' => function($route, $console) use ($serviceManager) {
$handler = new \Application\Command\DumbCommand();
return $handler($route, $console);
}
],
];
$config = $serviceManager->get('config');
$application = new Application(
$config['app'],
$config['version'],
$routes,
Console::getInstance(),
new Dispatcher()
);
$exit = $application->run();
exit($exit);
The handler function can use the service manager to inject any dependencies to the command handler:
'handler' => function($route, $console) use ($serviceManager) {
/** #var \Doctrine\ORM\EntityManager $entityManager */
$entityManager = $serviceManager->get(\Doctrine\ORM\EntityManager::class);
/** #var mixed $repository */
$contactRepository = $entityManager->getRepository(\Application\Entity\Contact::class);
$handler = new \Application\Command\DumbCommand($contactRepository);
return $handler($route, $console);
}
The command class is placed in a Command folder, it looks like:
<?php
namespace Application\Command;
use Application\Entity\Contact;
use Application\Repository\ContactRepository;
use Zend\Console\Adapter\AdapterInterface;
use ZF\Console\Route;
class DumbCommand
{
/** #var ContactRepository */
private $contactRepository;
public function __construct($contactRepository)
{
$this->contactRepository = $contactRepository;
}
/**
* #param Route $route
* #param AdapterInterface $console
* #throws \Doctrine\ORM\ORMException
*/
public function __invoke(Route $route, AdapterInterface $console)
{
$console->writeLine('Bob was here');
foreach ($this->contactRepository->findAll() as $item) {
/** #var Contact $item */
$console->writeLine($item->getFirstName() . ' was here');
}
}
}
(
This is my solution:
I addedd console command routes to my module.config.php files
'console' => array(
'commands' => array(
array(
'name' => 'sendemail',
'handler' => PostCommand::class,
),
array(
'name' => 'sendsms',
'handler' => SmsTransferCommand::class,
)
)
),
I created a console.php in /public (this will be run with arguments to start a CLI app)
use Zend\Console\Console;
use Zend\ServiceManager\ServiceManager;
use ZF\Console\Application;
use ZF\Console\Dispatcher;
chdir(dirname(__DIR__));
require_once 'vendor/autoload.php'; // Composer autoloader
// Prepare application and service manager
$appConfig = require 'config/application.config.php';
$application = Zend\Mvc\Application::init($appConfig);
$serviceManager = $application->getServiceManager();
// Load modules
$serviceManager->get('ModuleManager')->loadModules();
$config = $serviceManager->get('config');
$routes = $config['console']['commands']; // This depends on your structure, this is what I created (see. 1.)
$application = new Application(
$config['app'],
$config['version'],
$routes,
Console::getInstance(),
new Dispatcher($serviceManager) // Use service manager as a dependency injection container
);
$exit = $application->run();
exit($exit);
I separated my CLI command handlers into the src/Command folder. My CLI command handlers are services I have defined, created by factories. (This is why I use the service manager as the container - see. 2.)
[serviceEmail here is a local class variable, which is loaded by the factory of this command handler.]
/**
* #param Route $route
* #param AdapterInterface $console
*
* #return int
*/
public function __invoke(Route $route, AdapterInterface $console)
{
$mails = $this->serviceEmail->sendMailFromDb();
$console->writeLine('Sent mails: ' . \count($mails), ColorInterface::WHITE, ColorInterface::RED);
return 0;
}

Dynamic Laravel Socialite Configurations

I need to configure my providers dynamically.
$config = [
'client_id' = 'xxxxxxx',
'client_token' = 'xxxxxxx',
'redirect' = 'http://example.com/'
];
return Socialite::with($provider)->setConfig($config)->redirect();
But unfortunately there is no function setConfig.
I need to set provider, client_id, client_secret and redirect dynamically
Is there any ideas?
Thank you!
You could use the Socialite buildProvider method like:
$config = [
'client_id' = 'xxxxxxx',
'client_token' = 'xxxxxxx',
'redirect' = 'http://example.com/'
];
return Socialite::buildProvider(\Laravel\Socialite\Two\FacebookProvider::class, $config);
Where \Laravel\Socialite\Two\FacebookProvider::class would be swapped with your service (if different) as provided in either folder One/Two in https://github.com/laravel/socialite/tree/2.0/src
I use the following service provider in order to automatically fill in the redirect for each provider where it's empty.
It could be modified to update your configuration on the fly. It depends exactly what you're trying to do I suppose.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class SocialServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
collect(config('services'))
->only(config('social.providers'))
->reject(function($config) {
return array_get($config, 'redirect', false);
})
->each(function($config, $key) {
$url = url("login/{$key}/callback", [], true);
config(["services.{$key}.redirect" => $url]);
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
}
}
This could help if anyone still faces the problem
you can set the Redirect Url manually
$driver = Socialite::driver('google');
$driver->redirectUrl('your-custom-url');

Categories