R
R
Roman Yamchuk2017-05-18 10:47:27
Laravel
Roman Yamchuk, 2017-05-18 10:47:27

Why is the view receiving a field in json?

There are models: Questions and Blocks (categories of questions). One question can only be in 1 block. A block can contain multiple questions
Question.php

class Question extends Model
{
    public function block() {
    	return $this->belongsTo('App\Block');
    }
}

block.php
class Block extends Model
{
    public function questions() {
    	return $this->hasMany('App\Block');
    }
}

QuestionController.php
class QuestionController extends Controller
{

    public function index() {

    $questions = Question::all();

    return view('question.index')->with('questions', $questions);
    }
}

Now the crux of the problem:
When I try to display the name of the question block, I get the error Trying to get property of non-object The same block of code returns json: {"id":1,"name":"\u0411\u043b\u043e\u043a 1" }
<td>{{ $question->block->name }}</td>
<td>{{ $question->block }}</td>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Novikov, 2017-05-18
@tomgif

Try Or do a eager load first:

class QuestionController extends Controller
{

    public function index() {

    $questions = Question::all()->load('block');

    return view('question.index')->with('questions', $questions);
    }
}

and then call in the template as you called:
<td>{{ $question->block->name }}</td>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question