Skip to content

Instantly share code, notes, and snippets.

@CarterBland
Created October 9, 2018 18:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CarterBland/598faab1f6b89f15663f4da8f8397c95 to your computer and use it in GitHub Desktop.
Save CarterBland/598faab1f6b89f15663f4da8f8397c95 to your computer and use it in GitHub Desktop.
Push Token Trait for Laravel
<?php
namespace App\Traits;
use App\PushToken;
trait PushTokenTrait {
/**
* Notifies all
*
* @param String $title
* @param String $message
* @param Array $data
* @param Boolean $reciept
* @return void| Array
* @author
*/
static function notifyAll(
string $title,
string $message,
array $data = null,
boolean $reciept = null
)
{
$pushTokens = array_map(
function($pushToken) {
return $pushToken['push_token'];
},
PushToken::all()->toArray()
);
for($i = 0; $i < ceil(count($pushTokens) / 100); $i++) {
$request = curl_init();
$json = json_encode(
array_map(
function($pushToken) use ($title, $message, $data) {
return [
'to' => $pushToken,
'title' => $title,
'message' => $message
];
},
array_slice($pushTokens, $i * 100, $i * 100 + $i + 99)
)
);
curl_setopt_array($request, [
CURLOPT_URL => 'https://exp.host/--/api/v2/push/send',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json'
],
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json
]);
curl_exec($request);
}
}
/**
* Notifies all
*
* @param String $title
* @param String $message
* @param Array $data
* @param Boolean $reciept
* @return void| Array
* @author
*/
public function notify(
string $title,
string $message,
array $data = null,
boolean $reciept = null
)
{
$request = curl_init();
$json = json_encode([
'to' => $this->push_token,
'title' => $title,
'message' => $message
]);
curl_setopt_array($request, [
CURLOPT_URL => 'https://exp.host/--/api/v2/push/send',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json'
],
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json
]);
curl_exec($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment