
php
🚀
laravel
🚀
slack
🚀
Super Simple Sending Messages to Slack from Laravel
Laravel 5.3 has this feature. But for those not using that version or who just want to see how easy this is, I will show here how I been doing this for some time now.
Here is the main Class I call to send a message. As you can see I am using Guzzle, in this case "guzzlehttp/guzzle": "^6.1"
but others versions can work.
<?php
namespace App\Services;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;
class SlackWrapper
{
/**
* @var Client $client
*/
protected $client;
protected $slack_url = false;
public function __construct(Client $client)
{
$this->client = $client;
}
public function sendMessageToSlack($message)
{
try {
$this->client->request(
'POST',
$this->getSlackUrl(),
[
'body' => $this->message($message)
]
);
} catch (\Exception $e) {
Log::debug(sprintf("Error sending to Slack %s", $e->getMessage()));
}
}
protected function message($message)
{
return json_encode(
[
'text' => $message
]
);
}
public function getSlackUrl()
{
if (!$this->slack_url)
return env('SLACK_URL');
return $this->slack_url;
}
/**
* @param boolean $slack_url
*/
public function setSlackUrl($slack_url)
{
$this->slack_url = $slack_url;
return $this;
}
}
And that is it. As long as I set this env('SLACK_URL')
in my .env OR in the class instantiation it will get to that endpoint.
Then in slack just add get the webhook/room you want to post to