1
votes

I have a controller which gets an array of a User's diaries from my database and passes them to my view:

<?php

public function readDiaries($hash)
{
    $user = User::where('hash', $hash)->first();
    $diaries = Diary::where('user_id', $user->id)->get();

    return view('app.diary.readDiaries', ['diaries' => $diaries]);
}

In my view, I am looping through the diaries using a @foreach loop.

<div id="diaries" class="card-columns">
    @if (count($diaries) > 0)
        @foreach ($diaries as $dairy)
            {{ var_dump($diary) }}
        @endforeach
    @endif
</div>

But I am getting the following undefined variable error...

Undefined variable: diary (View: C:\xampp\htdocs\personal_projects\Active\diary_app\resources\views\app\diary\readDiaries.blade.php)

Why is my $diary variable undefined inside the @foreach loop?

4
just it is mistypingSaidbakR
just spell mistake in foreach $dairy and in vardump $diaryRitesh Khatri
maybe just mark this as typo?Rotimi

4 Answers

5
votes

You have a typo

change @foreach ($diaries as $dairy) to @foreach ($diaries as $diary)

and it should work!

2
votes

There is some typo in var_dump use {{ var_dump($dairy) }} Try to use compact method for pass data to view as shown below

 //return view('app.diary.readDiaries', compact('diaries'));
public function readDiaries($hash)
{
    $user = User::where('hash', $hash)
        ->first();
    $diaries = Diary::where('user_id', $user->id)
        ->get();
    return view('app.diary.readDiaries', compact('diaries'));
}
2
votes

It is just a simple spelling mistake,

 @foreach ($diaries as $dairy)
  {{ var_dump($diary) }}
 @endforeach

in your foreach you are passing $dairy and dumping var name is $diary chane it to

@foreach ($diaries as $dairy)
  {{ var_dump($dairy) }}
@endforeach

Habbit of copy paste is sometimes good for us... :)

1
votes
@foreach ($diaries as $dairy)
 {{ var_dump($diary) }}
@endforeach

you used ($diaries as $dairy) in foreach but in foreach you used ($diary)

you want edit this {{ var_dump($diary) }} to {{ var_dump($dairy) }} or you want edit @foreach ($diaries as $dairy) to @foreach ($diaries as $diary)