laravel - 尝试获取非对象的属性“android_id”时出错
问题描述
我想使用 laravel 向 android 设备发送通知。我不想使用包,我正在使用 curl 发送查询。我正在编写此代码但它有错误但它得到错误 Trying to get property 'android_id' of non -目的 。
我正在创建 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;
}
在控制器中:
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
}
}
和我的溃败:
Route::get('firebase/notification', 'firebaseNotificationController@notifyUser');
我的数据库:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('android_id')->nullable()->after('wallet');
});
}
解决方案
$user = User::where('id', $request->id)->first();
first() 方法的结果可能为 null,因为错误的 id 或请求参数为 null,您应该先检查它:
$user = User::where('id', $request->id)->first();
if($user==null)
{
// fail finding user code
}
else
{
$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
}
}
推荐阅读
- javascript - Javascript String#replaceAll 仅适用于一个实例
- docker - 使用 root 以外的用户会导致权限被拒绝
- python-3.x - 如何修复 curl django rest 框架?
- c# - 缩小窗口时不触发视觉状态
- php - Symfony 5 - 在实体中注入安全服务不起作用
- angular - 使用反应式表单编辑和添加页面的一种视图
- ios - UIActivityViewController 在呈现时以一种奇怪的方式动画
- android - 我可以使用 std::unique_lock 从 JNI AttachCurrentThread 和 DetachCurrentThread 吗?
- android - 如何平滑加速度计的值,以将其显示在画布上?
- javascript - Microsoft Graph 的 MSAL 配置