Skip to content
Advertisement

Data not passed correctly from Laravel controller to blade view **ONLY IN PRODUCTION**

//profile.blade.php

<form action="{{ $isFollowing ? route('unfollow', $user->username) : route('follow', $user->username) }}" method="post">
    @csrf
    <button type="submit">{{ $isFollowing ? 'Unfollow' : 'Follow' }}</button>
</form>
// ProfileController.php

public function index()
{
    $reqUsername = request()->route()->parameter('username');

    $user = User::where('username', $reqUsername)
        ->with(['followers', 'records' => function($query) {
            $query->with('likes');
        }])
        ->firstOrFail();

    if ($user->followers->count()) {
        foreach ($user->followers as $follower) {
            $isFollowing = $follower->id == auth()->id();
        }
    } else {
        $isFollowing = false;
    }

    return view('users.profile', [
        'user' => $user,
        'isFollowing' => $isFollowing
    ]);
}

I have recently encountered a problem with my Laravel application when deployed to Heroku. Just to note, this has been working just fine in production until very recently. The above snippets still work as intended in dev using Laravel Valet; However, in production, the $isFollowing variable is always returned to the view as bool(false) regardless of whether the data shows that the user whose profile we are on is being followed by the currently authenticated user.

Things I have tried thus far;

  1. dd($isFollowing) in production. Where I would expect that this would show either true or false when we hit the route, in production, I am seeing false preceded by a caret character => ^ False.

  2. Explicitly setting all conditional values and comparisons i.e. if ($user->followers->count() > 0) rather than if ($user->followers->count()).

What I am currently looking into;

  1. Could an update to one of the composer packages (or PHP/Laravel/Composer versions) have caused this issue? I haven’t made any changes to these myself so maybe this could have been an automatic update on Heroku’s part?

Thanks in advance for any help on this issue.

Advertisement

Answer

So, I didn’t figure out what was causing this bug but a slight change to my controller code seems to have fixed the issue.

public function index()
{
    $reqUsername = request()->route()->parameter('username');

    $user = User::where('username', $reqUsername)
        ->with(['followers', 'records' => function($query) {
            $query->with('likes');
        }])
        ->firstOrFail();

        return view('users.profile', [
            'user' => $user,
            'isFollowing' => $user->followers->contains('id', auth()->id())
        ]);
    }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement