首页 > 解决方案 > 尝试获取非对象的属性“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');
    });
}

标签: laravel

解决方案


$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
        }
}

推荐阅读