Laravel 7, several variables in the same View

Asked

Viewed 134 times

-2

Good morning, I’m developing a little project on Laravel 7 and I’m having a little trouble. This is the first time I have used Foreign key and several variables in the same Controller and View index. So far I’ve been able to create the Database tables with Foreign key and I think that in Controller everything is correct, at least there are no errors, but in View index is giving error from the moment I start using the second variable, "Trying to get Property 'data_type' of non-object", this is the error you make when loading the View index in your browser.

In the View index code is what I have,

@foreach($forms as $form)
    <tr>
        <td>{{ $form->name_form }}</td>
        <td>{{ $form->description }}</td>
        <td>{{ $form->email }}</td>
        <td>{{ $form->end_date }}</td>
        <td>{{ $form->question->data_type }}</td>
        <td>{{ $form->question->question }}</td>
        <td><a href="{{route('forms.edit', $form->id)}}" class="btn btn-info">Editar</a></td>
    </tr>
@endforeach

I wonder if someone can help me, it is the first time I contact several variables in the same View and I am not able to correct the error.

  • You could put your controller’s method in charge of returning this view?

1 answer

1

Your variable $form->question is not an object and you cannot access its properties using the reference arrow ->. Check the type of this variable and whether it is actually coming or is null;`

Make a dd($form->question) and check what’s coming from the controller;

possible solution 1 - the variable is null:

replace the lines below:

<td>{{ $form->question->data_type }}</td>
<td>{{ $form->question->question }}</td>

for:

@if(!empty($form->question))
    <td>{{ $form->question->data_type }}</td>
    <td>{{ $form->question->question }}</td>
@endif

possible solution 2 - the variable is an array instead of an object:

replace the lines below:

<td>{{ $form->question->data_type }}</td>
<td>{{ $form->question->question }}</td>

for:

@if(!empty($form->question))
    <td>{{ $form->question['data_type'] }}</td>
    <td>{{ $form->question['question'] }}</td>
@endif

Browser other questions tagged

You are not signed in. Login or sign up in order to post.