Reputation: 309
First sorry, i am only developing in php for a month and i do not know how to update this with laravel
I would like to update multiple photos.
Photos have a title description, etc.
My problem is i have no clue how to do it.
I tried the following
public function update(Request $request, Photo $photo)
{
// loop through array of id's
foreach ($request->photo_id as $id)
{
// find
$photos = $photo->find($id);
// loop throug input fields
foreach ($request->except('_token', 'tags', 'photo_id') as $key => $value)
{
$photos->$key = $value;
$photos->save();
}
}
die();
}
I get the following error
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
So i figured out the problem is with the value
And the results are like this
Key variable
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
Value variable results
array(2) {
[0]=>
string(9) "title one"
[1]=>
string(9) "title two"
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
}
array(2) {
[0]=>
string(0) ""
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
I tried several other attempts but nothing works
Could please someone help me out with this?
Upvotes: 4
Views: 1704
Reputation: 4012
Without knowing more about what is passing you the request object, I can't really go into specifics but you probably want to get your request object to look something like this:
'photos' => [
{
'id' => 1,
'title' => 'title one',
// more properties ....
},
{
'id' => 2,
'title' => 'title two',
// more properties ....
},
]
Then try something like this:
public function update(Request $request)
{
// Loop through the request photo id's
$request->photos->each(function($photo) use ($request) {
// Return the photo object you want to update
$photo = Photo::find($photo->id);
// Get the things you want from the request and update the object
$photo->title= $request[$photo_id]->title;
// Save the object
$photo->save();
})
}
You also may want to try out the dd();
function instead of die();
. It makes debugging a lot easier.
Upvotes: 1
Reputation: 1379
I think, Photo Model missed the fillable array.
protected $fillable = ['var1', 'var2', ...];
Upvotes: 0