如何在Laravel 5.3中将关联数据传递给可邮寄对象?

3

我可以为laravel使用背包(喜欢它)。

所以,每当用户存储数据时,我有这段代码(FinanceCrudController):

    $finance = $request->all();
    if ($request->input('shouldPay') == 'Yes') {
        Mail::to($request->user())->send(new NewBill($finance));
        return parent::storeCrud();
    } 
    else {
        return parent::storeCrud();
    }

这是我的可邮寄类(NewBill)的样子:

class NewBill extends Mailable
{
    use Queueable, SerializesModels;


    /**
     * The finance instance.
     *
     * @var Finance
     */
    public $finance;


    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($finance)
    {
        //
        $this->finance = $finance;
    }

    /**
     * Build the message.
    *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.newbill');
    }
}

我可以通过在 newbill.blade.php 中这样调用,从财务表中传递数据:

{{ $finance['name'] }}

然而,我还没有完全搞清楚如何获取关系数据。

我正在使用一个分类表来处理分类。因此,如果我在我的Blade视图中调用该类别:

{{ $finance['category_id'] }}

我只想获得Category表中该字段的ID号。

如何在电子邮件中显示实际的类别名称,而不是该字段的ID号?

1个回答

2

您定义在可邮寄类上的任何公共属性都会自动提供给视图。因此,您可以执行以下操作:

public $finance;
public $category;

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

public function build()
{
    $this->category = \App\Category::where('id', $this->finance['category_id'])->first();
    return $this->view('emails.newbill');
}

然后在视图中使用$category->name来访问类别名称。

https://laravel.com/docs/5.3/mail#view-data


1
太好了!感谢你的帮助! - Rosenberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接