响应内容必须是实现__toString()的字符串或对象,在移动到 psql 后给出的“布尔值”内容

2022-08-30 12:55:36

一旦我将Laravel应用程序从MySQL移动到pSQL。我一直收到这个错误。

响应内容必须是实现__toString())的字符串或对象,给出的“布尔值”。

我有一个 API,假设要返回我的促销

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

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

它曾经返回我的促销,现在它返回一个错误。


dd($promotion);

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

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


答案 1

您的响应必须返回某种对象。您不能只返回一个对象。Response

因此,请将其更改为:

return Response::json($promotion);

或者我最喜欢的使用帮助程序函数:

return response()->json($promotion);

如果返回响应不起作用,则可能是某种编码问题。请参阅此文章:响应内容必须是实现 __toString(), \“布尔值”给定的字符串或对象。


答案 2

TL;DR

只是返回并不能解决这个问题中的问题。 是一个雄辩的对象,Laravel 会自动json_encode响应。json 编码失败,因为该属性是 PHP 流资源,无法编码。response()->json($promotion)$promotionimg

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

因此,当您仅从控制器操作中时,Laravel将调用它以将其转换为要显示的字符串。return $promotion__toString()

在 上,调用 ,返回 的结果。因此,返回 ,这意味着它遇到错误。Model__toString()toJson()json_encodejson_encodefalse

您的表示您的属性是 . 无法对 a 进行编码,因此这可能会导致失败。应将特性添加到属性中,以将其从 中删除。ddimgstream resourcejson_encoderesourceimg$hiddenjson_encode

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

    // rest of class
}

推荐