SQLSTATE [HY000]:常规错误:1364字段'almt_kec'没有默认值(SQL:插入
kecamatans
(nm_kec
,nm_camat
,{{1} },updated_at
)值(Bangkinang,Pak Camat,2018-10-26 04:08:32,2018-10-26 04:08:32))
这是我的代码
created_at
这是我的模特
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Kecamatan;
class KecamatanController extends Controller
{
public function index(){
$kecamatans = Kecamatan::orderBy('created_at', 'DESC')->paginate(10);
return view('kecamatan.index', compact('kecamatans'));
}
public function store(Request $request){
//validasi
$this->validate($request, [
'namaKecamatan'=>'required|string|max:50',
'namaCamat' => 'required|string|max:50',
'alamatKantor' => 'required|string|max:50',
'teleponKantor' => 'required|string|max:50',
'keteranganKecamatan' => 'nullable|string'
]);
try{
$kecamatans = Kecamatan::firstOrCreate([
'nm_kec' => $request->namaKecamatan
],[
'nm_camat' => $request->namaCamat
],[
'almt_kec' => $request->alamatKantor
],[
'tlp_kec' => $request->teleponKantor
],[
'ket_kec' =>$request->keteranganKecamatan
]);
return redirect()->back()->with(['success' => 'Kecamatan : ' .$kecamatans->nm_kec .
' Ditambahkan']);
} catch (\Exception $e) {
return redirect()->back()->with(['error' => $e->getMessage()]);
}
}
//
}
这是我的观点
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Kecamatan extends Model
{
protected $fillable = ['nm_kec','nm_camat','almt_kec','tlp_kec','ket_kec'];
//
}
你能帮我吗?
答案 0 :(得分:0)
firstOrCreate
方法将尝试使用给定的列/值对查找数据库记录。如果在数据库中找不到模型,则会插入一条记录,其中包含第一个参数的属性以及可选的第二个参数的属性。
$kecamatans = Kecamatan::firstOrCreate([
'nm_kec' => $request->namaKecamatan, // A
], [
'nm_camat' => $request->namaCamat, // B
], [
'almt_kec' => $request->alamatKantor,
], [
'tlp_kec' => $request->teleponKantor,
], [
'ket_kec' => $request->keteranganKecamatan,
]);
因此,您尝试搜索nm_kec
( A ),然后仅插入nm_camat
( B )。
尝试更改您的$kecatamans
:
$kecamatans = Kecamatan::firstOrCreate([
'nm_kec' => $request->namaKecamatan,
'nm_camat' => $request->namaCamat,
'almt_kec' => $request->alamatKantor,
'tlp_kec' => $request->teleponKantor,
'ket_kec' => $request->keteranganKecamatan,
]);
Mungkin karena Pak Camat nya lagi gak ada di kantor哈哈。