未定义变量$errors在模式形式的Laravel



打开modal时出现错误。这是我的代码:

<div>
<x-button onclick="viewFormAdd()" data-bs-toggle="modal" type="button">Add New Data</x-button>
</div>
<script>
function viewFormAdd() {
$.get("{{ route('kategori.create') }}", {},
function(data, status) {
$('.viewmodal').html(data).show();
$('#modalCreateKategori').modal('show');
}
);
}
</script>

createKategori.blade.php

<x-modal modalId="modalCreateKategori" modalTitle="Tambah Kategori">
<form method="post" action="{{ route('kategori.store') }}" class="formtambah">
@csrf
<div class="grid grid-rows-2">
<div>
<x-label>Nama Kategori</x-label>
<x-input type="text" name="nama_kategori" id="nama_kategori" />
@error('nama_kategori')
<small>{{ $message }}</small>
@enderror
</div>
<div class="justify-end items-center">
<x-button type="submit">Simpan</x-button>
</div>
</div>
</form></x-modal>

AJAX:

<script>
$(document).ready(function() {
$('.formtambah').submit(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "post",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: "json",
success: function(response) {
if (response.tersimpan) {
Swal.fire({
position: 'center',
icon: 'success',
title: 'Tersimpan!',
text: response.tersimpan,
showConfirmButton: false,
timer: 1500
})
$('.btn-close').click();
dataKategori();
}
},
error: function(xhr, thrownError) {
alert(xhr.status + "n" + xhr.responseText + "n" + thrownError);
}
});
return false;
});
});</script>

My Controller:

public function create()
{
return view('kategori.createKategori');
}
/**
* Store a newly created resource in storage.
*
* @param  IlluminateHttpRequest  $request
* @return IlluminateHttpResponse
*/
public function store(KategoriRequest $request)
{
$kategori = new Kategoris;
$kategori->namakat = $request->nama_kategori;
$kategori->save();
$msg = [
'tersimpan'=> 'Produk baru berhasil tersimpan!'
];
return response()->json($msg);
}

My categororirequest:

class KategoriRequest extends FormRequest{
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'nama_kategori' => 'required'
];
}
public function messages()
{
return[
'nama_kategori.required' => 'Maaf, nama kategori harus diisi'
];
}

}

当我打开模态时,模态不工作并得到错误"未定义的变量$errors(视图:C:xampphtdocsnewsinartimur_laravel_9resourcesviewskategori createkategori .叶片.php)">

当我检查浏览器标签网络时,我看到了这个

Request URL: http://localhost:8000/api/kategori/create
Request Method: GET
Status Code: 500 Internal Server Error
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin

但是当删除

@error('nama_kategori')
<small>{{ $message }}</small>
@enderror

的模态和形式工作正常。我不明白这个错误。

实际上,在访问@error('nama_kategori')之前需要先检查@if ($errors->any());所以试试这个

@if ($errors->any())
@error('nama_kategori')
<small>{{ $message }}</small>
@enderror
endif

最新更新