如何在Laravel中使用数组访问数据库值

时间:2018-06-15 04:46:29

标签: php laravel

我正在创建一个网站。所以,我已经将数据存储在数据库中。现在我想查看两个不同表中的数据。然后我尝试了下面的方法。但是,它给了我这个错误 -

Trying to get property 'firstname' of non-object (View: D:\wamp64\www\cheapfares\resources\views\invoices\des.blade.php)

但是,显然firstname在数据库表中。

我该如何解决这个问题?

控制器页面。 (InvoicesController.blade.php)

public function userinvoice($terms = '',$invoiceNo = '')
    {

        $invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();

        $tr = DB::table('termsandconditions')
            ->where('topic', $terms)->get()->first();

        $twoar = [];
        $twoar['inv'] = $invoice;
        $twoar['trms'] = $tr;

        return view('invoices.des', ['twoar' => $twoar]);

    }

查看页面。 (des.blade.php)

{{$twoar['inv']->firstname}}

{{$twoar['trms']->topic}}

路线。

Route::get('/invoice/adminuser-invoice/{invoiceno}', [
    'uses' => 'InvoicesController@adminuserinvoice',
    'as' => 'invoice.adminuser'
]);

2 个答案:

答案 0 :(得分:0)

尽管将响应转换为Array可能是一个合适的解决方案,但异常的原因很可能在于数据库中没有有效的条目。

您可以像这样改进代码以减轻这种影响:

public function userinvoice($terms, $invoiceNo)
{
    // Load invoice, or throw ModelNotFoundException/404 without valid entries.
    $invoice = Invoice::where('invoicereference', $invoiceNo)->firstOrFail();

    // load the terms.
    $terms = DB::table('termsandconditions')
        ->where('topic', $terms)->first();


    return view('invoices.des', compact('invoice', 'terms'));

}

在这个例子中,我在路由中提出了$terms$invoiceNo义务参数。确保查询将提供正确的结果。此外,firstOrFail()现在需要发票条目,条款是可选的。我不是将两个变量都分配给一个数组,而是将它们都发送到视图中,这样你就可以正确地声明它们的值,而不会使用数组键访问造成混乱。

您的观点:

{{$invoice->firstname}}

{{$terms->topic}}

答案 1 :(得分:0)

请尝试以下代码:

public function userinvoice($terms = '',$invoiceNo = '')
{

    $invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();

    $tr = DB::table('termsandconditions')
        ->where('topic', $terms)->get()->first();



    return view('invoices.des', ['tr'=>$tr,'invoice'=>$invoice]); //Directly pass the mulitple values into  the view


}

您的观看页面如下:

 {{$invoice->firstname}}
   {{$tr->topic}}

它可以帮助你的朋友。

相关问题