1
0

More than 1 year has passed since last update.

入力フォームのinputの値が、配列形式の場合にカンマ区切りでDB登録。

Last updated at Posted at 2022-02-19

#はじめに
実務で、複数選択可能な入力フォームの値をDBにカンマ区切りで登録する場面があったので自分用のメモとして残します。

入力フォームで業種タイプが医療、ITサービス、ペット販売という風に複数選択されており
name属性がindustryで、inputのvalueが配列形式で下記のようになっている場合

<?php
$params = $request->all(); 

//現状、$request->get('industry')の値は、array(0 => 1, 1 => 2, 2 => 3)という状態
if (!empty($request->get('industry'))) {
   $str_industry = implode(",", $params['indsutry']); //配列の中の各値を、一つずつカンマ区切りに修正する。
   $params['indsutry'] = $str_industry; //登録対象の値を、カンマ区切りにした値に書き換える。
} else {
   $params['indsutry'] = '';
}

DB:beginTransaction();

try {
    $create_company = companie::create($params); //登録処理
} catch (Exception $e) {
    Log::notice(print_r($e->getMessage(), true));
    DB::rollBack();
    return $this->sendError(500, 'サーバーエラーが発生しました');
}
    DB::commmit();
}
  
?>

以上です。

追記

Laravelの$castsを使用して、配列として扱いたい
値を下記ページを参考にして定義すると上記のような処理は不要でした。。

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0