Home > front end >  Laravel: getting data from an array inside an array
Laravel: getting data from an array inside an array

Time:02-03

This is my query repository. The idea is to create a query table (CreateRequest is the Model, stuff I can't control), and to do that, I must fill six tables, 5 of them behaving the same way.

The tables are requests and sectors, and I have no problems with the bit of the request, but I'm struggling with the others.

This is what print_r says I send to my repository.

Array
(
    [type] => loan
    [project_value_min] => 500
    [project_value_max] => 1000
    [sector_name] 
    => Array 
        (           
              [0] => Technology           
              [1] => Agriculture
        )
)

And here's what I've tried

DB::beginTransaction();

$request = CreateRequest::create([
    'type' => $data['type'],
    'project_value_min' => $data['project_value_min'],
    'project_value_max' => $data['project_value_max'],
]);

foreach ($data as $value) {
    foreach ($value->sector_name as $key) {
        if ($key != null) {
            $sector = Sector::create([
                'sector_name' => $key['sector_name'],
                'request_id' => $request->id,
            ]);
        }
    }
}

And many other similar variants.

The response:

"message": "Attempt to read property "sector_name" on string", "exception": "ErrorException",

CodePudding user response:

You are trying to access a property on a string instead of an array. Try the following.

DB::beginTransaction();

$request = CreateRequest::create([
    'type'=> $data['type'],
    'project_value_min' => $data['project_value_min'],
    'project_value_max'=> $data['project_value_max'],
]);

foreach($data['sector_name'] as $key){
    if($key !== null){
        $sector = Sector::create([
           'sector_name' => $key,
           'request_id' => $request->id,
        ]);
    }
}
  • Related