Updating Nested Arrays with Laravel

Sorry first, I am only developing in php for a month and I don't know how to update this with laravel

I would like to update some photos.

Photos have a description of the name, etc.

My problem is that I have no idea how to do this.

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 realized that the problem is related to the value

And the results look 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"

Variable Value 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

Can anyone help me with this?

+4
source share
2 answers

, , , , , , :

'photos' => [
    {
        'id' => 1,
        'title' => 'title one',
        // more properties ....
    },
    {
        'id' => 2,
        'title' => 'title two',
        // more properties ....
    },
]

- :

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();
    })
}

dd(); die();. .

+1

, Photo Model .

protected $fillable = ['var1', 'var2', ...];
0

All Articles