Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 处理非对象_Laravel_Laravel 5 - Fatal编程技术网

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