简体   繁体   English

在 Laravel/PHP 中将多项选择转换为数组,返回 Err:Array 到字符串转换

[英]Casting multiple choice to array in Laravel/PHP returning Err:Array to string Conversion

I am trying to create a small Pizza ordering app using Laravel, the objective of this question is to add toppings into an SQL column called toppings.我正在尝试使用 Laravel 创建一个小型披萨订购应用程序,此问题的目的是将浇头添加到名为 toppings 的 SQL 列中。

Everything works as intended apart from the toppings.除了浇头外,一切都按预期工作。 If the user selects multiple toppings to be added the options will need to be combined into an array and then into a string value within the toppings sql column.如果用户选择要添加的多个浇头,则需要将选项组合到一个数组中,然后组合到浇头 sql 列中的字符串值中。 The resource I am following shows their mySQL table with:我关注的资源显示了他们的 mySQL 表: 资源 sql 结果

Please notice the final column [toppings], an array of toppings selected.请注意最后一列 [toppings],选择了一系列配料。

I have tried to incorporate this on my own, I have also looked at other resources and followed them to the "T" but still the issue is there.我试图自己合并它,我还查看了其他资源并将它们跟踪到“T”,但问题仍然存在。

I must say everything is working correctly just not the toppings.我必须说一切正常,只是浇头没有。

I have taken screenshots as I believe it would be easier to understand.我已经截取了屏幕截图,因为我相信它会更容易理解。

html 网页表单

This is the webform layout, toppings[array] specified for each topping checkbox.这是 webform 布局,为每个顶部复选框指定了 toppings[array]。 The migrations:迁移:

CreatePizza_Migration

As we can see json has been specified for toppings.正如我们所见,json 已被指定用于浇头。

The PizzaController:比萨控制器:

比萨控制器

I am requesting the toppings that have been selected.我要求已选择的浇头。

比萨模型

According to the resources I am following image 5 seems to be the issue.根据我正在关注的资源,图5似乎是问题所在。 When I go onto the route pizza/create - which works and enter a name and select a few toppings as shown here.当我 go 到路线 Pizza/create - 工作并输入名称和 select 一些配料时,如图所示。

比萨网络表单

Note: even if you select a single topping the next error presents itself.注意:即使您 select 一个单一的顶部,下一个错误也会出现。

数组到字符串的转换

I am not sure how to fix this, if anybody has any ideas.如果有人有任何想法,我不确定如何解决这个问题。 I would greatly appreciate it, if more information is required please let me know.我将不胜感激,如果需要更多信息,请告诉我。

Thank you in advance.先感谢您。

The solution depends on the laravel version but try adding a mutator for saving the toppings:解决方案取决于 laravel 版本,但尝试添加一个 mutator 来保存浇头:

/**
     * Set the pizza's toppings.
     *
     * @param  string  $value
     * @return void
     */
    public function setToppingsAttribute($value)
    {
        $this->attributes['toppings'] = json_encode($value);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM