vendredi 6 juillet 2018

LARAVEL 5.5 - Saving arrays to database

I've got an array which I've passed into my view which consists of the following:

array:353 [▼
0 => "Company name"
1 => "Another name"
....
]

Suppose a user has selected both options above. Whilst I'm able to successfully save multiple choice options from the form in my database, I need to save the name rather than the number. For example, in phpmyadmin, the target_companies column is saved as ["0", "1"] rather than [Company name", "Another name"].

I'm passing this data into my view with the following:

$companies = DB::table('vacancies')->distinct()->select('company')->pluck('company')->toArray();

In my view, I've got this:

VIEW

<div class="form-group">
  
  
</div>

And in my controller, I've got the following:

CONTROLLER

public function update(Request $request)
{
  $this-> validate($request, [
      'target_sector' => 'required|max:255',
      'target_skillsets' => 'required|max:255',
      'target_companies'=> 'required|max:255',
      'target_locations'=> 'required|max:255',

  ]);
  //Create Post
  $id = Auth::user()->id;
  $admin = Admin::find($id);
  $admin->target_companies = $request->input('target_companies');
  $admin->target_sector = $request->input('target_sector');
  $admin->target_skillsets = $request->input('target_skillsets');
  $admin->target_locations = $request->input('target_locations');

  $admin->save();

  return redirect('/admin')->with('success', 'Preferences Updated', 'admin',$admin);
}

Finally, the model has this:

protected $casts= [
 'target_companies'=> 'array',
];



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire