array_merge():期望参数1是一个数组,使用集合作为事件参数时给出的对象

问题描述 投票:0回答:2

现在我正在使用 Laravel 8.26 和 Pusher 4.1。

这是我的活动:

class NotifSeller implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $fields;

    public function __construct($fields)
    {
        $this->fields = $fields->toArray();
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        // return new PrivateChannel('notif-seller.'.$this->fields->seller_id);
        return new PrivateChannel('notif-seller.'.$this->fields->seller_id);
    }

    public function broadcastWith()
    {
        $message = $this->fields;
        return $message;
    }
}

这是我的控制器:


        $t = new Transaksi();
        $t->item_id = $request->item_id;
        $t->seller_id = $request->seller_id;
        $t->buyer_id = $request->buyer_id;
        $t->category = 'merchandise';
        $t->amount = $request->amount;
        $t->save();
        
        event(new NotifSeller($t));
        return redirect()->back()->with('status', 'Success');

它会显示错误消息

array_merge(): Expected parameter 1 to be an array, object given

我这里的代码有错吗?我查了很多教程,在他们的教程中他们可以使用集合作为事件参数,但是当我尝试它时,它变成这样。

抱歉,如果我的英语不好,我不是英语母语,这是我第一次在 Stack Overflow 上提问,所以我希望你能理解。预先感谢。

php laravel parameters pusher
2个回答
0
投票

很可能是因为您正在使用

SerializesModels
Laravel 尝试序列化您的
public $fields;
属性,因为它包含一个模型。

不同的潜在解决方案:

  • 尝试输入 prop
    public array $fields;
  • 将整个模型保存在那里
    public Transaksi $fields;
  • 删除
    SerializesModels
    特征,技术上不需要。

0
投票

您可以通过调用(链接)Laravel中的 toArray() 方法将集合转换为数组。

例如:

$collection = collect(['name' => 'Desk', 'price' => 200]);

$array = $collection->toArray();

或者

$array = collect(['name' => 'Desk', 'price' => 200])->toArray();


/* result

    [
        ['name' => 'Desk', 'price' => 200],
    ]

*/
© www.soinside.com 2019 - 2024. All rights reserved.