“数组到字符串的转换"; errorr Laravel-尝试将数组保存到数据库 [英] "Array to string conversion" errorr Laravel - Trying to save array to database

查看:78
本文介绍了“数组到字符串的转换"; errorr Laravel-尝试将数组保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我是Laravel的新手,第一次尝试将其保存到数据库.我试图将数组保存到数据库,但出现错误数组到字符串的转换".我尝试将迁移文件中的字符串值更改为其他选项,但出现相同的错误.

Sorry Im new to Laravel and trying to save to the database for the first time. Im trying to save an array to the database but the error "array to string conversion" is appearing. I've tried changing the string value in the migration file to other options but the same error is appearing.

控制器

    public function store(Request $request)
{   
    Myroutes::create([ //posting to acc table
        'start' => $request->start,
        'end' => $request->end,
        'waypoints' => $request->waypoints
    ]);

    return redirect('/');
}

迁移

 public function up()
{
    Schema::create('myroutes', function (Blueprint $table) {
        $table->increments('myroute_id');
        $table->integer('user_id');
        $table->string('start');
        $table->string('end');
        $table->string('waypoints');
        $table->timestamps();
    });
}

模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Myroutes extends Model
{
    protected $fillable = [
        'user_id',
        'start',
        'end',
        'waypoints'
    ];
}

查看

<div id="dynamicInput" class="form-group">
                    <label>Additional Destinations</label>
                    <input type="text" name="waypoints[]" class="form-control" autocomplete="on">
                </div>

数据库表

数据库img

推荐答案

您遇到错误:'waypoints' => $request->waypoints将不起作用,因为$request->waypoints是一个数组,并且无法将数组保存到一个数组中. VARCHAR()字段.如果您implode输入,并将其转换为逗号分隔的字符串,则应该可以正常工作:

You've got an error: 'waypoints' => $request->waypoints won't work, as $request->waypoints is an array, and you can't save an array into a VARCHAR() field. If you implode the input, and convert it to a comma-separated string it should work alright:

`'waypoints' => implode(",", $request->waypoints`)

话虽如此,这通常被认为是一个坏主意;考虑清楚和易于使用(尤其是在检索/编辑中),请考虑使用RoutesWaypoints之间的关系作为单独的表.

That being said, this is generally considered a bad idea; consider using relationships between Routes and Waypoints as separate tables, for both clarity and ease of use (especially in retrieving/editing.)

这篇关于“数组到字符串的转换"; errorr Laravel-尝试将数组保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆