Krystian Polska
Krystian Polska

Reputation: 1356

Strange thing in Laravel where on dd() it's ok, without it's 'not an object'?

Code:

    @foreach($room->students as $student)
         <li>
         {{ $student->student->first_name }}
         <a href="{{ route('student.show', $student) }}">{!! "{$student->student} {$student->last_name}" !!}</a>
        </li>
   @endforeach

This is a relation the $student

public function student()
    {
        return $this->belongsTo(Student::class);
    }

$student is actually here an room_student model. And this model belongsTo student.

The problem is?

The $student->student->first_name produces this error:

enter image description here

However this should work, because $student->student gives Student object as well because of relation (I gave code too).

So changing this line {{ $student->student->first_name }} to {{ dd($student->student) }} works good and produces this result:

enter image description here

And even better, look what we will get from this {{ dd($student->student->first_name) }}

enter image description here

Oh, it's great yeah? It works?

Nope, because once I take off the dd() function to it look like this: {{ $student->student->first_name }}...

enter image description here

Oh, again. Hello darkness my old friend...

So what is happening here? Why? Why with dd() works perfectly? Without doesn't? What is going on?


die(var_dump()) on this

enter image description here

This is object. 100%. What is going on? Possible framework bug?

Upvotes: 1

Views: 823

Answers (2)

user6138421
user6138421

Reputation:

I had an issue like this before and i used multidimensional array to pass back the data. So in this case you might have to use this, it is very strange indeed. Hope this helps.

$student->student['0']['first_name'];

Upvotes: 0

ankit patel
ankit patel

Reputation: 1918

Seems like you need to put if condition before

@if(isset($student->student->first_name)
     $student->student->first_name
@endif

when you put dd($student->student) in your code, it was the first record in your loop and you got this error within your loop on one of the elements in the object, because of you don't have student relationship attached with one of your element in the loop.

that's why you need to attach if condition as I mentioned above.

Upvotes: 1

Related Questions