Home > Software design >  Undefined variable $followings overtrue/laravel-follow
Undefined variable $followings overtrue/laravel-follow

Time:12-21

I'm getting this error however using dd($followings); in the home controller, the date is displayed, but when I try to foreach the view, I get this error.

Does anyone have an idea what I'm doing wrong?

Undefined variable $followings

HomeController

public function userFollow($username)
{
    $user = User::where('username', $username)->firstOrFail();

    $posts = Post::where('user_id', $user->id)->simplePaginate(3);
    $user = User::find($user->id);
    $followings = $user->followings()->with('followable')->get();

    dd($followings);
    return view('/@', compact('user'), compact('posts'), compact('followings'));

}

view @.blade.php

@foreach($followings as $following)

 {{$following->id}}

@endforeach

dd($followings); returns

  #attributes: array:7 [▼
    "id" => 60
    "user_id" => 5
    "followable_type" => "App\Models\User"
    "followable_id" => 9
    "accepted_at" => "2022-12-20 20:36:49"
    "created_at" => "2022-12-20 20:36:49"
    "updated_at" => "2022-12-20 20:36:49"

CodePudding user response:

Use compact() like this

return view('/@', compact('user', 'posts', 'followings'));

Or use with()

return view('/@')->with(['user' => $user, 'posts' => $posts, 'followings' => $followings]);
  • Related