kirschbaum-development / nova-mail

A Laravel Nova action that provides a mail sending form for any resource
MIT License
73 stars 25 forks source link

Accessing model relationships #50

Closed berendsendevelopment closed 2 years ago

berendsendevelopment commented 3 years ago

I am trying to access the model relationship for example a hasMany relation or belongsTo. I cant seem to get it working. I have a email model template in which i want to display the order lines which is linked trough a hasMany relation in the order model.

If i do the following in the blade file: @foreach ($orderlines as $orderline)

@endforeach

i get the following error: Undefined variable $orderlines

adammparker commented 3 years ago

Hey @berendsendevelopment, accessing relationships off the mailable model is not supported currently.

When we build the markdown Mail we expose all attributes/relationships on the model that are available via ->toArray(). That's not going to include unloaded relationships by default unfortunately.

Check out this code here: https://github.com/kirschbaum-development/nova-mail/blob/1.0.4/src/Mail/Send.php#L89

You could use the $with model property to always include the relationship. But the problem with this is your orderLines variable won't work since it's an array and that will cause the markdown to fail to build currently.

As a temporary fix, you could include an attribute on the mailable model getOrderLinesForEmailAttribute() for example, but this needs to essentially return a string of what you'd like the final variable to output in the markdown template.

Note: If you go this route you need to include this new attribute in the mailable model's $appends array. Something like:

protected $appends ['order_lines_for_email'];

This would be a cool piece of functionality to add in here but no "new feature" development is currently planned for this package. If you want to dip your toes in and contribute I'm more than happy to collaborate/review a PR!