一旦我把我的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
}内容

__有关这方面的任何提示/建议将是一个巨大的帮助!
发布于 2016-08-04 16:29:04
TL;DR
仅仅返回response()->json($promotion)并不能解决这个问题。$promotion是一个雄辩的对象,Laravel将自动将其作为响应的json_encode。由于img属性是PHP流资源,因此json编码失败,不能进行编码。
详细信息
无论您从控制器返回什么,Laravel都将尝试转换为字符串。当您返回一个对象时,将调用对象的__toString()魔术方法来进行转换。
因此,当您只是从控制器操作return $promotion时,Laravel将调用其上的__toString()将其转换为要显示的字符串。
在Model上,__toString()调用toJson(),后者返回json_encode的结果。因此,json_encode正在返回false,这意味着它遇到了一个错误。
dd显示您的img属性是一个stream resource。json_encode无法对resource进行编码,因此这可能是导致失败的原因。您应该将img属性添加到$hidden属性中,以便从json_encode中删除它。
class Promotion extends Model
{
protected $hidden = ['img'];
// rest of class
}发布于 2016-08-04 15:05:10
您的响应必须返回某种类型的Response对象。你不能只返回一个对象。
因此,将其改为如下:
return Response::json($promotion);或者我最喜欢使用助手函数:
return response()->json($promotion);如果返回响应不起作用,这可能是某种编码问题。参见本文:toString(), \"boolean\" given."
发布于 2017-02-13 14:59:15
当我使用ajax调用从数据库中检索数据时,我遇到了这个问题。当控制器返回数组时,它将其转换为布尔值。问题是我有“无效字符”,比如ú(带口音的u)。
https://stackoverflow.com/questions/38770871
复制相似问题