如何在Laravel中的控制器中定义变量

时间:2018-07-30 11:20:34

标签: laravel

我在刀片模板中使用的URL为:

    href="{{ route('download', ['year' => $year, 'month' => $month, 'file' => $file_path]) }}"

当我运行我的代码时,它给我一个错误,如下:

  

未定义变量:年份(视图:C:\ wamp64 \ www \ Blog \ employee-portal \ resources \ views \ finance \ invoice \ edit.blade.php)

如何在控制器中定义此$ year变量?

在我的控制器中,该函数编写为:

    public function download($year, $month, $file, $inline = true)
    {
        $headers = [
            'content-type' => 'application/pdf',
        ];

        $file_path = FileHelper::getFilePath($year, $month, $file);

        if (!$file_path) {
            return false;
        }

        if ($inline) {
            return Response::make(Storage::get($file_path), 200, $headers);
        }

        return Storage::download($file_path);
    }
}

编辑功能写为:

    public function edit(Invoice $invoice)
    {
        $projectStageBillings = $invoice->projectStageBillings;

        $projectStageBilling = $projectStageBillings->first();
        $client = $projectStageBilling->projectStage->project->client;
        $client->load('projects', 'projects.stages', 'projects.stages.billings');

        $billings = [];
        foreach ($projectStageBillings as $key => $billing) {
            $billing->load('projectStage', 'projectStage.project');
            $billings[] = $billing;
        }

        return view('finance.invoice.edit')->with([
            'invoice' => $invoice,
            'clients' => Client::select('id', 'name')->get(),
            'invoice_client' => $client,
            'invoice_billings' => $billings,
        ]);
    }

1 个答案:

答案 0 :(得分:0)

此错误表明视图finance\invoice\edit.blade.php缺少变量$year。的确如此,请看一下您的编辑功能的返回:

return view('finance.invoice.edit')->with([
    'invoice' => $invoice,
    'clients' => Client::select('id', 'name')->get(),
    'invoice_client' => $client,
    'invoice_billings' => $billings,
]);

您在此处没有向视图发送任何$year变量(发送到视图的变量是invoiceclientsinvoice_clientinvoice_billings

要解决您的问题,只需向视图发送$ year变量,您就可以了:)