Laravel 8 – can’t get data from database

What you need is to get all the followers of a user.
Let me do the coding for you so that you have a somewhat more standard code than you have now.

In you User Model

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The followers that belong to the User
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function followers()
    {
        return $this->belongsToMany(User::class, 'follow', 'user_id', 'follower_id');
    }
}

In your controller.

/**
 * Gets the user with all his followers.
 *
 * @param string $username
 * @return \Illuminate\Http\Response
 */
public function getProfile($username){

    $user = User::with('followers')->where('username', $username)->firstOrFail();
    
    return view('design2.profile', [
        'user' => $user,
    ]);
}

In your blade.

@foreach($user->followers as $follower)
    <h6>
        <span class="text-secondary">
            <strong>{{$follower->name}}</strong>
        </span>
    </h6>
@foreach

And that is all.

Leave a Comment