You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel8验证报错Expected type 'object'. Found 'array'解决

错误原因

抛出Expected type 'object'. Found 'array'的核心原因有两个:

  1. $request->validated()返回值是已经通过校验的数组类型数据,经过array_merge()拼接token字段后,$validated仍是纯数组,不存在validate()这个对象方法,用->操作符调用数组方法直接触发类型错误。
  2. 你已经通过依赖注入使用了自定义表单请求类VerifyRequest,Laravel框架的FormRequest本身自带自动验证逻辑:验证不通过时会自动跳转回来源页、闪存错误信息与用户输入,控制器里手动写的验证判断逻辑完全多余。

另外你的控制器代码末尾多写了Blade模板语法@endif,这行不属于PHP控制器代码,会额外触发语法错误,需要直接删除。

修复方案

1. 修正控制器代码

删除多余的手动验证判断块和无意义的@endif,修正后的verify方法代码如下:

public function verify(VerifyRequest $request)
{
    // 此处拿到的$validated已经通过VerifyRequest定义的全部校验规则,无需重复验证
    $validated = array_merge($request->validated(), ['token' => Str::random(127)]);

    // 创建投诉记录
    Pengaduan::create($validated);
    // 组装验证邮件参数
    $data = [
        'content' => 'to create complaint please click the link below',
        'url' => 'http://127.0.0.1:8000/complaint/create/' . $validated['token'],
    ];
    // 发送验证邮件
    Mail::to($validated['email'])->send(new VerifyAlternative($data));

    return redirect()
        ->route('complaint.check')
        ->with('success', 'Register success. Please Check your email');
}

FormRequest默认的失败跳转逻辑完全符合你的需求:自动返回上一页、携带错误信息、闪存表单输入,不需要手动调用withErrors()、withInput(),如果需要自定义跳转锚点,可以在VerifyRequest类里重写跳转属性实现。

2. 补全Blade模板的错误提示渲染

你当前模板只写了成功消息的渲染,需要补充错误消息的渲染逻辑,可根据你的需求选择实现方式:

方案A:和现有风格统一的Bootstrap行内提示

{{-- 成功提示 --}}
@if(session()->has('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
    {{ session('success') }}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endif

{{-- 验证错误提示 --}}
@if ($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <ul class="mb-0">
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endif

方案B:SweetAlert弹窗提示

如果需要用弹窗展示提示,在全局公共模板部分加入以下代码即可:

{{-- 成功弹窗 --}}
@if(session()->has('success'))
<script>
    Swal.fire({
        icon: 'success',
        title: '操作成功',
        text: '{{ session('success') }}',
        confirmButtonText: '确定'
    })
</script>
@endif

{{-- 错误弹窗 --}}
@if ($errors->any())
<script>
    let errorContent = '';
    @foreach($errors->all() as $error)
        errorContent += '{{ $error }}<br/>';
    @endforeach
    Swal.fire({
        icon: 'error',
        title: '提交失败',
        html: errorContent,
        confirmButtonText: '确定'
    })
</script>
@endif
补充说明

你在VerifyRequest中定义的prepareForValidation方法会自动在验证前拼接邮箱后缀,unique规则会自动校验拼接后的完整邮箱,不需要额外调整逻辑。

内容的提问来源于stack exchange,提问作者Kokurate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 05:48:28