首页 > 解决方案 > 控制器的视图中没有显示错误消息

问题描述

我正在尝试显示错误消息,但未显示。我可以在控制台(网络选项卡)中看到错误消息,但视图中没有任何内容。提前致谢。

API 的输出。

{"message":"The given data was invalid.","errors":{"title":["The title field is required."]}}

控制器:

public function store(Request $request)
{
    $request->validate([
        "title"=> "required"
    ]);
    try {
        if ($request->ajax()) {
            $request->merge(['created_by_user_info_id' => Auth::user()->id]);
            SavingTypes::create($request->all());
            $data['status'] = true;
            $data['title'] = null;
            $data['message'] = 'Added Successfully.';
        }
    } catch (\Exception $e) {
        $data['status'] = false;
        $data['message'] = 'Something went wrong. please try again';
        $data['error'] = $e->getMessage();
    }
    return $data;
}

看法:

<h1>{{ $errors->first('title') }}test</h1> // only the "test" is visible and theres no error msg although I can see the error msg in the console (Network tab)
<input type="text" class="form-control" placeholder="title" name="title" >

标签: laravel

解决方案


如果请求通过 AJAX 发送,那么您将无法访问

$errors->first('title')

您将在 JavaScript 中遇到错误

$.ajax({

    // some code
    
    
    error: function(jqXHR, textStatus, errorThrown) {
        // Here you will get errors
        console.log(textStatus, errorThrown);
    }
});

推荐阅读