I want to send notification to android devices using laravel.I do not want use package,and I am using curl to send query .I am write this codes but it has error but it gets the error Trying to get property 'android_id' of non-object .
I am create help.php
function send_notification_FCM($android_id, $title, $message, $id,$type) {
$accesstoken = env('FCM_KEY');
$URL = 'https://fcm.googleapis.com/fcm/send';
$post_data = '{
"to" : "' . $android_id . '",
"data" : {
"body" : "",
"title" : "' . $title . '",
"type" : "' . $type . '",
"id" : "' . $id . '",
"message" : "' . $message . '",
},
"notification" : {
"body" : "' . $message . '",
"title" : "' . $title . '",
"type" : "' . $type . '",
"id" : "' . $id . '",
"message" : "' . $message . '",
"icon" : "new",
"sound" : "default"
},
}';
// print_r($post_data);die;
$crl = curl_init();
$headr = array();
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: ' . $accesstoken;
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($crl, CURLOPT_URL, $URL);
curl_setopt($crl, CURLOPT_HTTPHEADER, $headr);
curl_setopt($crl, CURLOPT_POST, true);
curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
$rest = curl_exec($crl);
if ($rest === false) {
// throw new Exception('Curl error: ' . curl_error($crl));
//print_r('Curl error: ' . curl_error($crl));
$result_noti = 0;
} else {
$result_noti = 1;
}
//curl_close($crl);
//print_r($result_noti);die;
return $result_noti;
}
and in the controller :
public function notifyUser(Request $request){
$user = User::where('id', $request->id)->first();
$android_id = $user->android_id;
$title = "Greeting Notification";
$message = "Have good day!";
$id = $user->id;
$type = "basic";
$res = send_notification_FCM($android_id, $title, $message, $id,$type);
if($res == 1){
echo 'success';
// success code
}else{
// fail code
}
}
and my rout :
Route::get('firebase/notification', 'firebaseNotificationController@notifyUser');
my database:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('android_id')->nullable()->after('wallet');
});
}