问题描述
在 Laravel 13 中,通过 redirect()->with() 或 session()->flash() 存储的 MessageBag 对象,在 blade 模板中取出时会被序列化为数组,导致调用 ->get() 方法时报错:
Call to a member function get() on array
或者:
htmlspecialchars(): Argument #1 ($string) must be of type string, array given
影响范围
resources/views/partials/alerts.blade.php
resources/views/partials/toastr.blade.php
resources/views/partials/exception.blade.php
问题根源
ScaffoldController::backWithSuccess() 等方法创建 MessageBag 并通过 redirect()->with(compact('success')) 传到 session,但 Laravel 13 中序列化/反序列化行为发生了变化。
解决方案
添加公共方法 admin_session_message() 兼容处理 MessageBag 对象和数组:
if (! function_exists('admin_session_message')) {
function admin_session_message($data, string $key, string $default = ''): string
{
if ($data instanceof \Illuminate\Support\MessageBag) {
return (string) $data->first($key);
}
return (string) \Illuminate\Support\Arr::first((array) \Illuminate\Support\Arr::get($data, $key, $default));
}
}
兼容性
此修改兼容 Laravel 10、11、12、13。
问题描述
在 Laravel 13 中,通过
redirect()->with()或session()->flash()存储的MessageBag对象,在 blade 模板中取出时会被序列化为数组,导致调用->get()方法时报错:或者:
影响范围
resources/views/partials/alerts.blade.phpresources/views/partials/toastr.blade.phpresources/views/partials/exception.blade.php问题根源
ScaffoldController::backWithSuccess()等方法创建MessageBag并通过redirect()->with(compact('success'))传到 session,但 Laravel 13 中序列化/反序列化行为发生了变化。解决方案
添加公共方法
admin_session_message()兼容处理MessageBag对象和数组:兼容性
此修改兼容 Laravel 10、11、12、13。