How to pass a collection to mailable laravel

Viewed 733

How can I send a collection with mailable and organize in the view the items that I have created in a collection within an object?

In my controller I am creating an order like this:

$order = Order::create([
            'products' => json_encode(new CartItemCollection($items)),
            'price' => $PartialPrice,
            //other stuff
        ]);

In my purchase function, I am sending the email like this:

            $pro = $order->products;
            $data = [
                'extra_address' => $order->extra_address,
                'address' => $order->address,
            ];

            Mail::to($check_user->email)->send(new NewPurch($data, $pro));

In the configuration of my email I have this:

public $data;
public $pro;

public function __construct($data,$pro)
{
    $this->data = $data;
    $this->pro = $pro;
}


public function build()
{
    return $this->markdown('newpurch')->with(['data' => $this->data])->subject('Thank you');
}

And in the view, I receive the data, but I don't know how to access each one

@component('mail::message')

Someone want this:

{{$pro}}

@endcomponent

The email looks like: enter image description here

But I can´t acces as an object $pro->id or as a key $pro['id']

EDIT: If I try this:

@component('mail::message')

Someone want this:

@foreach($pro->items as $item)
  {{ $item->id }}
@endforeach

@endcomponent

Get this error:

Trying to get property 'items' of non-object (View: /app/resources/views/newpurch.blade.php)

And if I try this:

 @component('mail::message')

<?php
$deco = json_decode($pro,true);
?>
Someone want this:
  {{ $deco }}

@endcomponent

Get this error:

htmlspecialchars() expects parameter 1 to be string, array given (View: /app/resources/views/newpurch.blade.php)

1 Answers

EDIT:

public $data;
public $pro;

public function __construct($data, $pro)
{
    $this->data = $data;
    $this->pro = json_decode($pro, true);
}


public function build()
{
    return $this->markdown('newpurch')->with(['data' => $this->data])->subject('Thank you');
}

And use the foreach since we are now back to a collection instead of a string.

@foreach($pro->items as $item)
  {{ $item->id }}
@endforeach

Related