Laravel 处理非对象
我可能有这样一个控制器函数Laravel 处理非对象,laravel,laravel-5,Laravel,Laravel 5,我可能有这样一个控制器函数 public function index() { $poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first(); $question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->fir
public function index()
{
$poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
$answers = DB::table('poll_answer')->whereNull('deleted_at')->where('question_id', $question->id)->orderBy('id')->get();
return view('index', compact('poll', 'question', 'answers'));
}
如果我正在获取的三个集合包含数据,这是可以接受的。如果他们不这样做,而我尝试访问索引页,我会
PollResponseController.php第20行中的ErrorException:尝试获取非对象的属性
那么,处理非对象的最佳方法是什么?要绕过这个,我可以
public function index()
{
$poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
if($poll) {
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
if($question) {
$answers = DB::table('poll_answer')->whereNull('deleted_at')->where('question_id', $question->id)->orderBy('id')->get();
return view('index', compact('poll', 'question', 'answers'));
}
}
return view('error');
}
但这不是有点过分吗?我只是想知道是否有更好的方法来处理这个问题
谢谢您可以使用simple if$question子句或ifis_null$question
在刀片模板中,它将分别类似于@if$question和@ifis_null$question
@if($question)
{{ $question->property }}
@endif
在大多数情况下,您应该绕过模板中的所有变量,然后使用@if子句检查每个变量
@if($question)
{{ $question->property }}
@endif