如何在Laravel中以json的形式返回值?

时间:2017-08-22 04:31:37

标签: php laravel

在我的控制器中,我返回了一行像

 $alarm= \DB::table('vwAlarmActionSummaryYFUserSite')
            ->where([['vwAlarmActionSummaryYFUserSite.yfUserID', '=', $yfUserID], ['vwAlarmActionSummaryYFUserSite.AlarmId', '=', $id]])->first();

当我这样做时;

 var_dump( $alarm);

它给出了;

object(stdClass)#249 (59) { ["AlarmId"]=> string(6) "246733" ["AlertTypeId"]=> string(2) "23" ["AlertTypeName"]=> string(20) "Missing Data - Sales" ["AlertTypeDescription"]=> string(20) "Brownout Sales Alarm" ["AlertSourceSystemId"]=> string(1) "1" ["AlertSourceSystemName"]=> string(7) "HD SIRA" ["AlertId"]=> string(7) "9957057" [
...........

我将其传递到我的View页面,如;

return view('alarms.ack', ['alarm' => $alarm, 'yfSessionId' => $yfSessionId]);

在View I中访问属性,如;

$alarm->SiteCode 
$alarm->AlarmId

现在,我得到了这个例外;

 ErrorException
Cannot use object of type stdClass as array (View: /app/resources/views/alarms/ack.blade.php)
at CompilerEngine->handleViewException(object(FatalThrowableError), 0)
in PhpEngine.php (line 46)
at PhpEngine->evaluatePath('/app/storage/framework/views/c593810096345df8c818851d1e61ae4bc523a3d4.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'alarm' => object(stdClass), 'yfSessionId' => 'abc'))
in CompilerEngine.php (line 59)

我怎样才能克服这个?

2 个答案:

答案 0 :(得分:0)

//控制器

 $data = return response()->json($alarm);
return view('alarms.ack', compact('data'));

//视图

{!! $data->SiteCode !!}

答案 1 :(得分:-1)

 $value = return response()->json( array('result'=>array('data'=>$alarm)));