Not sure whether best or not.?
Can give a try with your query inside loop...
for($i = 0; $i < count($yourArray); $i++){
//add you insert query
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hey
I've currently got an ajax script which allows me to select pictures and grab their ID. It posts the ids as an array to my controller but I'm having issues working out how best to save it.
My db structure looks like
ID | picture_id | picture_owner
The data that my ajax script posts looks like:
Array[3]
0: "123"
1: "456"
2: "789"
I'm wanting each of these values to have their own row on the DB and post through the Auth::user()->id as well. How am I best dealing with the data in the controller?
Thanks!
Not sure whether best or not.?
Can give a try with your query inside loop...
for($i = 0; $i < count($yourArray); $i++){
//add you insert query
}
Ok it seems happy with that but what should I be putting as my picture_id on the insert query?
$request->all()
?
Well, you didn't tell us what the parameter name is that it's being posted as, but lets assume it's images
Do something like this:
$images = $request->get('images');
for ($i = 0; $i < count($images); $i++) {
Image::create([
picture_id => $images[$i],
picture_owner => Auth::id()
]);
}
instead of for you could also do a foreach loop:
foreach ($images as $image_id) {
...
}
I'd rather not run multiple queries within a loop. Be conservative about hitting the database.
$arr = [];
for ($i = 0; $i < count($images); $i++) {
array_push($arr, ['picture_id' => $images[$i], 'picture_owner' => auth()->id]);
}
Image:insert($arr);
Hey
Thanks to everyone for the really helpful responses! All are coming back with 'success' but actually none are appearing in the database.
The model has the correct fillable fields and the code itself works fine - just nothing is actually being inserted...
insert would be fine in this case, since it's probably a pivot table being updated here, rather than a model with other attributes that aren't populated unless you are using eloquent.
I'm probably explaining this badly! It's not passing the 'picture_id' from the ajax into the DB. Here's the function:
public function store(Request $request) {
$storePicture = new PicturePrice;
$images = $request->get('array');
for($i = 0; $i < count($image); $i++) {
$storePicture->picture_id = $i;
$storePicture->picture_owner = Auth::user()->id;
$storePicture->price = '10';
$storePicture->save();
}
}
Ajax is:
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".user-images" ).click(function() {
$( this ).toggleClass( 'selected');
});
$( "#saveImages" ).click(function() {
let array = [];
$(".selected").each(function() {
array.push($(this).attr("data-picture-key"));
});
console.log(array);
$.ajax({
type: "POST",
url: "images/add",
data: array,
success: function() {
console.log('success');
}
});
});
});
</script>
This logs success and spits out the image ids in the console and I get no errors, but when I check the DB, nothing is there.
for($i = 0; $i < count($image); $i++) {
$storePicture->picture_id = $i;
$storePicture->picture_owner = Auth::user()->id;
$storePicture->price = '10';
$storePicture->save();
}
$i is not the value, it's the index in the array. change that to $image[$i];
D'oh! Stupid typo, corrected that but still nothing being inserted!
I can't think of any reason at all - there are no errors, the table name and field names are correct, the data is being posted. What gives?
You also have a typo in your for statement.. count of $image will be 0 since it's not defined.
Also since you're not instantiating a new PicturePrice image during each pass through the loop at best your code would insert one entry, then rewrite it several times so you end up with a single entry with just the last picture id. Instead try this:
public function store(Request $request) {
$images = $request->get('array');
foreach($images as $id) {
PicturePrice::create([
'picture_id' => $id,
'picture_owner' => Auth::user()->id,
'price' => '10',
]);
}
}
or indeed as @usama.ashraf suggested:
public function store(Request $request) {
$images = $request->get('array');
$data = [];
foreach($images as $id) {
$data[] = [
'picture_id' => $id,
'picture_owner' => Auth::user()->id,
'price' => '10',
];
}
PicturePrice::insert($data);
}
That makes perfect sense and thanks for the heads up on the typo! Code ought to be working now but I'm getting a 500 error stating that 'array' is null and so the foreach fails.
My guess is that the ajax script isn't passing the data in that case?
Yeah your javascript is wrong.. you need to pass it as something...
$.ajax({
type: "POST",
url: "/images/add",
data: {
picture_ids: array
},
success: function() {
console.log('success');
}
});
Also, array is really a terrible variable name.. ;)
public function store(Request $request) {
if ($ids = $request->get('picture_ids')) {
foreach($ids as $id) {
PicturePrice::create([
'picture_id' => $i;
'picture_owner' => Auth::user()->id;
'price' => 10;
]);
}
// return something
}
// return a failure message indicating no ids were provided
}
Haha! That works perfectly, thanks so much!
Agreed re the variable name and I'm going to study this a bit more till I get to grips with it. Thanks :)
Please or to participate in this conversation.