微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – Response内容必须是实现__toString()的字符串或对象,移动到psql后给出“boolean”

只要我将Laravel应用程序从MySQL移动到psql.我一直收到这个错误.

The Response content must be a string or object implementing __toString(), “boolean” given.

我有一个API,假设要退回我的促销活动

http://localhost:8888/api/promotion/1

public function id($id){
    $promotion = Promotion::find($id);
    dd($promotion); //I got something here
    return $promotion;
}

它曾用于返回我的促销,现在它返回错误.

DD($推广);

I got 

Promotion {#410 ▼
  #table: "promotions"
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:16 [▼
    "id" => 1
    "cpe_mac" => "000D6721A5EE"
    "name" => "qwrqwer"
    "type" => "img_path"
    "status" => "Active"
    "heading_text" => "qwerq"
    "body_text" => "werqwerqw"
    "img" => stream resource @244 ▶}
    "img_path" => "/images/promotion/1/promotion.png"
    "video_url" => ""
    "video_path" => ""
    "account_id" => 1001
    "img_url" => ""
    "footer_text" => "qwerqwerre"
    "created_at" => "2016-08-04 10:53:57"
    "updated_at" => "2016-08-04 10:53:59"
  ]
  #original: array:16 [▶]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #fillable: []
  #guarded: array:1 [▶]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

内容

enter image description here

__
任何关于此的提示/建议都将是一个巨大的帮助!

解决方法:

TL; DR

只返回response() – > json($promotion)将无法解决此问题中的问题. $promotion是一个Eloquent对象,Laravel将自动json_encode作为响应.由于img属性一个PHP流资源,json编码失败,无法编码.

细节

无论您从控制器返回什么,Laravel都会尝试转换为字符串.返回对象时,将调用对象的__toString()魔术方法进行转换.

因此,当您从控制器操作返回$promotion时,Laravel将在其上调用__toString()将其转换为要显示的字符串.

在Model上,__ toString()调用toJson(),它返回json_encode的结果.因此,json_encode返回false,这意味着它遇到了错误.

您的dd显示您的img属性一个流资源. json_encode无法对资源进行编码,因此可能导致失败.您应该将img属性添加到$hidden属性以将其从json_encode中删除.

class Promotion extends Model
{
    protected $hidden = ['img'];

    // rest of class
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐