Skip to content

fix: Laravel 13 兼容性 - session 中 MessageBag 被序列化为数组 #24

@PrintNow

Description

@PrintNow

问题描述

在 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。

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions