![](/img/trans.png)
[英]Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, null given .. Error to post data
[英]Laravel 7 dynamic "add fields" form. foreach() argument must be of type array|object, null given
這是我在這里的第一篇文章,但絕不是我第一次訪問。 我是一名業余編碼員,我正在做一些讓我難過一兩天的事情......
我正在使用 Laravel 7 構建一個站點。其中一個頁面包含一個動態表單,允許用戶根據需要添加字段。
我正在生成動態表單字段和 tinymce 編輯器,並使用 javascript 提交表單。
我遇到的問題是這樣的:
單擊“提交”按鈕后,頁面不會轉換或顯示任何已提交的跡象。 表單數據的第一部分已成功提交並添加到相應的數據庫表中,但動態字段未添加到它們的表中,並且在瀏覽器控制台中引發錯誤。
相信相關問題是message "foreach() argument must be of type array|object, string given"
,因為這似乎是代碼停止運行的地方並且 go 錯誤。
此 function 適用於表單的動態image_id[]
部分。
完整的錯誤信息是:
XHR POST https://www.mydomainname.com/create
[HTTP/1.1 500 Internal Server Error 479ms]
要求:
format "galleries"
title "This+is+the+title+of+the+content"
short "This+is+the+short+description+for+the+content."
thumb "https://www.mydomainname.com/storage/giraffe1.jpg"
category "funny"
image_id […]
0 "Image+1"
1 "Image+2"
2 "Image+3"
回復:
message "foreach() argument must be of type array|object, string given"
exception "ErrorException"
file "/home/user/site/app/Http/Controllers/ContentController.php"
line 149
trace [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
第 149 行:
foreach($request->input('image_id[]') as $key => $image) {
這是我的刀片視圖,包括Javascript :
@extends('layouts.app')
@section('title', 'Post New Content')
@section('content')
<script src="https://cdn.tiny.cloud/1/arx09ivbx1ikchqgcvc6558h9sx2crokpd2c1152g667mh0c/tinymce/6/tinymce.min.js"></script>
<script src="/vendor/laravel-filemanager/js/stand-alone-button.js"></script>
<div class="container">
<div class="row">
<div class="col-md-8">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none">
<ul></ul>
</div>
<div class="card shadow">
<h2 class="card-header">
Post a New Gallery
<a class="btn btn-danger" style="float: right" href="{{ url()->previous() }}" onclick="return confirm('Are you sure? All progress will be lost!')">Go Back</a>
</h2>
<div class="card-body">
<form name="add_name" id="add_name">
<input type="hidden" name="format" value="galleries" class="form-control" required>
<div class="form-group row mb-0">
<div class="col-md-12">
<strong>Title:</strong>
<input type="text" name="title" class="form-control" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-12">
<strong>Description:</strong>
<input type="text" name="short" class="form-control" required>
</div>
</div>
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<strong>Thumbnail:</strong>
<div class="input-group">
<div class="col-md-10">
<input type="text" id="thumb" class="form-control" name="thumb" aria-label="thumb" aria-describedby="button-image" required>
</div>
<div class="col-md-2">
<div class="input-group-append">
<button class="btn btn-primary" type="button" id="button-image">Browse</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<strong>Category: </strong>
<select name="category" class="form-control" required>
<option value="" disabled selected>Select content category...</option>
@foreach($allCategories as $category)
<option value="{{ $category->name }}">{{ ucfirst(trans($category->name)) }}</option>
@endforeach
</select>
</div>
</div>
</div>
<br>
<!-- Dynamic Fields -->
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="image_id[]" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
<!-- End Dynamic Fields -->
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var postURL = "<?php echo url('create'); ?>";
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added">' +
'<td><input type="text" name="image_id[]" class="form-control name_list" /></td>' +
'<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td>' +
'</tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
if(data.error){
printErrorMsg(data.error);
}else{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display','block');
$(".print-error-msg").css('display','none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$(".print-success-msg").css('display','none');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('button-image').addEventListener('click', (event) => {
event.preventDefault();
window.open('/file-manager/fm-button', 'fm', 'width=1400,height=800');
});
});
// set file link
function fmSetLink($url) {
document.getElementById('thumb').value = $url;
}
</script>
@endsection
這是我的Controller :
public function createPost(Request $request)
{
$post = new Content();
$post->title = $request->get('title');
$post->short = $request->get('short');
$post->long = $request->get('long');
$post->thumb = $request->get('thumb');
$post->format = $request->get('format');
$post->category = $request->get('category');
$post->author = Auth::user()->id;
$post->save();
$order = 0;
foreach($request->input('image_id[]') as $key => $content) {
$contentImg = new ContentImages();
$contentImg->content_id = $post->id;
$contentImg->image_id = $content->image_id;
$contentImg->image_order = $order+1;
$contentImg->save();
}
return response()->json(['success'=>'done']);
}
最后,我的路線:
Route::get("create","ContentController@create");
Route::post("create","ContentController@createPost");
我嘗試過的事情
我已經嘗試了 image_id 語法的幾種變體,但似乎沒有任何效果......
如上貼:
foreach() argument must be of type array|object, null given
使用$request->input('image_id')
:
"Attempt to read property \"image_id\" on string"
我試過$request('image_id')
並得到:
Object of type Illuminate\Http\Request is not callable
然后我嘗試$request->input(['image_id'])
剛剛給出
foreach() argument must be of type array|object, null given
dd($request->input('image_id')
中的 output 是:
array:2 [
0 => "Name 1"
1 => "Name 2"
]
和dd($request->input('image_id[]'))
給了null
。
Output of dd($request->all())
:
array:6 [
"format" => "galleries"
"title" => "Thoughtless Driver Ruins Everyone's Day at the Wildlife Park"
"short" => "This lady made a mess at the West Midland Safari Park. The Giraffe was not injured."
"thumb" => "https://www.mydomainname.com/storage/photos/1/6317a2b460c98.jpg"
"category" => "oops"
"image_id" => array:3 [
0 => "Name 1"
1 => "Name 2"
2 => "Name 3"
]
]
我真的迷失了這個。
非常感謝這里的任何指導,以及有關處理這種情況的更好方法的任何建議。
我是一個有點天賦的業余愛好者,但遠非專家,我一直在尋找學習。
非常感謝提前!!
SMR
好的,所以我弄清楚我做錯了什么。
$request->input('image_id')
是正確的解決方案。
我的問題進一步下降。 一旦我更正為$request->input('image_id')
,這會導致另一個錯誤"Attempt to read property \"image_id\" on string"
,但這實際上是由於頁面下方的語法錯誤。
解決了這個問題,現在一切都很好!
感謝那些幫助過的人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.