如何在Laravel中将数组转换为字符串?

我正在使用引导程序形式从数组中的复选框值中获取输入。我正在使用数组存储复选框值。我如何将这个数组转换为string。因为数据库仅采用字符串值。


这是我的代码


<div class="form-group col-md-12">

    <div class="custom-control custom-checkbox custom-control-inline">

        <input type="checkbox" id="eduPrimary" name="education[]" 

        class="custom-control-input" value="primary" />

        <label class="custom-control-label" for="eduPrimary">primary</label>

    </div>

</div>

<div class="form-group col-md-12">

    <div class="custom-control custom-checkbox custom-control-inline">

        <input type="checkbox" id="eduSecondary" name="education[]" 

        class="custom-control-input" value="secondary" />

        <label class="custom-control-label" for="eduSecondary">secondary</label>

    </div>

</div>

<div class="form-group col-md-12">

    <div class="custom-control custom-checkbox custom-control-inline">

        <input type="checkbox" id="eduUniversity" name="education[]" 

        class="custom-control-input" value="university" />

        <label class="custom-control-label"for="eduUniversity">university</label>

    </div>

</div>

在后端,我正在使用laravel将值存储到数据库中,但是在mysql中将数组存储为字符串时会运行错误。


public function store(Request $request,AdProfile $adprofile)

{

    $adprofile->education = $request->education[];

    $adprofile->save();

    return redirect()->route('adprofile.profilecomplete');

}


PIPIONE
浏览 1162回答 3
3回答

幕布斯7119047

&nbsp;print_r($request->education); //It is an array print$str_json = json_encode($request->education); //array to json string conversionecho&nbsp; $str_json; // printing json stringprint_r(json_decode($str_json)); //printing array after convert json string to arrayexit; // exiting further execution to check resutls

万千封印

您可以implode为此使用php ,也可以为此使用laravel集合。继承人collect([1, 2, 3, 4, 5])->implode('-');// '1-2-3-4-5'请参阅此Implode的文档或者您可以使用php函数内爆看到这个$arr = array('Hello','World!','Beautiful','Day!');echo implode(" ",$arr);//Hello World! Beautiful Day!

白板的微信

在您的“ AdProfile”模型中添加属性强制转换变量,以便laravel将数组自动转换为json并将json转换为数组,像这样<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class AdProfile extends Model{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* The attributes that should be casted to native types.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @var array&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; protected $casts = [&nbsp; &nbsp; &nbsp; &nbsp; 'education' => 'array',&nbsp; &nbsp; ];}
打开App,查看更多内容
随时随地看视频慕课网APP