在控制器中使用对象

时间:2019-02-20 21:21:17

标签: php laravel

当前,我有一个函数可以将查询的原始结果作为对象返回。所以这个:

Items.php

public static function getItems($item){

$sql = "
        SELECT count(*) as items from itemTable where itemNumber = {$item};
    ";

    $result = DB::select(DB::raw($sql));

    return $result;
}

直接转储时,返回对象:

"items":15

问题是,我正在控制器中访问它,当我尝试在刀片上转储“ $ items”时,它为空

控制器:

$itemFile = new Items();
$items= $itemFile->getItems($item);

return view('test.blade')
    ->with('items', $items);

刀片:

dd($items);

但是如果我放

$results = DB::select(DB::raw("SELECT count(*) as items from itemTable where itemNumber = {$item}"));
dd($results);

然后我将物体放在刀片上方。

如何正确地将其传递到刀片服务器中

2 个答案:

答案 0 :(得分:3)

第一个建议清理您的Item类:

<?php 

public static function getItemCount($item){

    //  Using PDO binding to avoid SQL injections
    $result = DB::select('SELECT count(*) as itemCount from itemTable where itemNumber = :item', [ 'item' => $item ]);

    return $result[0]->itemCount;
}

DB::select()返回一个数组,即使您使用的是计数查询。所以我正在使用[0]索引

然后在您的控制器中:

$itemCount = (new Items())->getItemCount($item);

return view('test.blade', compact('itemCount'));

然后您将可以使用变量{{ $itemCount }}

答案 1 :(得分:0)

您可以像下面的代码那样将变量传递给刀片:

view( "your.blade.view", [ "items" => $items ] );

或第二种方法:

View::Share( 'items', items );