0

I'm following a tutorial from Laracasts and I'm making a clone of Twitter. I've got a home.blade.php and a HomeController.php file. In the HomeController I've got a function called index, which calls the home view. He also sends a variable called "tweets".

public function index()
{
    return view('home', [
        'tweets' => App\Tweet::all()
    ]);
}

In the home.blade.php file I use blade to show the variable, but I get this error: Undefined variable: tweet (View: C:\wamp64\www\laravel\tweety\resources\views\home.blade.php)

Here's my home.blade.php file:

@extends('layout')
@section('timeline')
<article>
    <div class="avatar">
        <img src="https://www.w3schools.com/w3css/img_avatar2.png" />
    </div>
    <div class="content">
        <div class="meta">
            <span class="author">
                {{ $tweet->user->name }}
            </span>
            <span class="time">
                &bullet; 10m
            </span>
        </div>
        <div class="text">
            {{ $tweet->body }}
        </div>
    </div>
</article>
@endsection

I've searched on the internet to a solution, but couldn't find one. If you need more information, please tell me.

Thank you! Jeroen van Rensen

STA
  • 30,729
  • 8
  • 45
  • 59
JeroenvanRensen
  • 3
  • 1
  • 2
  • 6
  • 1
    You are returning `tweets` not `tweet`. I think you'll have to loop over `$tweets` to print each tweet attributes. https://laravel.com/docs/7.x/blade#loops – porloscerros Ψ May 26 '20 at 15:48
  • Hello porloscerros, I'm running a loop over `$tweets`, so that isn't the problem. But thanks for your answer – JeroenvanRensen May 26 '20 at 16:09

1 Answers1

1

$tweets is an array. You need foreach loop. It loops over the array, and each value for the current array element is assigned to $tweet

Try this :

@extends('layout')
@section('timeline')
@foreach($tweets as $tweet)
<article>
    <div class="avatar">
        <img src="https://www.w3schools.com/w3css/img_avatar2.png" />
    </div>
    <div class="content">
        <div class="meta">
            <span class="author">
                {{ $tweet->user->name }}
            </span>
            <span class="time">
                &bullet; 10m
            </span>
        </div>
        <div class="text">
            {{ $tweet->body }}
        </div>
    </div>
</article>
@endforeach
@endsection
STA
  • 30,729
  • 8
  • 45
  • 59
  • Hello, thanks for your answer. Now he does work. But isn't there an option so I can keep the article in the home.blade.php file? That looks a little bit cleaner – JeroenvanRensen May 26 '20 at 16:08