Home > other >  Create array key inside foreach loop in laravel
Create array key inside foreach loop in laravel

Time:04-03

I'm fetching data from database, inside foreach loop i have to add one array index list_array

  $list = Lists::where('name',$request->name)->get();
   $Data=[];
   foreach($list as $key => $list_row)
   {
    $list_row['list_array'][]=$list_row['data_1'];
    $list_row['list_array'][]=$list_row['data_2'];
    $Data[]=$list_row;
   }

It should be of array type but when i declare it as array it is not working,

message: "Indirect modification of overloaded property App\Models\Lists

Any solution to create list_array as an array index inside foreach loop. Thanks

CodePudding user response:

You are not dealing with an array, you are dealing with an App/Models/Lists model. What you probably instead want to do is adding a custom attribute to the model. This happens one step before.

// your model

class Lists 
{
   protected $appends = ['list_array'];
    
   public function getListArrayAttribute()
   {
        $data = [
            // your array data from where ever 
        ];
    
        return $data;
   }
}

You then can access (without adding it when you want to access the data) the new attribute from within the model, like so:

// where you access your data

$lists = Lists::where('name', 'whatever')->get();
    
foreach($lists as $list) {
    dd($lists->list_array)
}

You can read more about the so called Accessors here:

https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor (Laravel 8) https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor (Laravel 9)


I hope I got the intention of your question right. From your question it's not very clear what data you want to add and where it is coming from. There might be other and better ways too.

Edit:

Based on the comment from @user3653474 the Accessor function could look like this.

public function getListArrayAttribute()
{
     $data = [
         $this->data_1,
         $this->data_2,
     ];
    
    return $data;
}

data_1 and data_2 are the column names in the table of the same model.

  • Related