1
votes

I want to search users by ($_POST['search'] '"name" and "lastname"') that follows the

"user id = 1"

I got the table users, in users I got

"name" and "lastname"

And I got the table followers, in followers I got

"follower_id" and "user_id"...

I know that to do it I have to use models related, but I don't know how...

//$user_id = 1 (in followers.user_id)
//$_POST['search'] (in users.name and users.lastname)

public function u_followers_search($user_id) {

$followers = ...

return $followers;

}
1
Take a look at this article ! - Maraboc
do you already have the relations? - Maraboc

1 Answers

0
votes

You need to set up a relationship on your User model:

function followers() {
    return $this->hasMany(Follower::class)
}

This will enable you to do:

$userId = 1 // or however you get the user id
$user = User::findOrFail($userId)->followers;

EDIT:

With the relationship it means you will be able to get all the followers that follow a specific user:

$allFollowers = User::findOrFail($userId)->followers;

This will give you all Users that follow User with id 1

You can then continue the query and add your matching criteria

$allFollowers->where('name', 'like', '%' . $search . '%')
             ->orWhere('lastname', 'like', '%' . $search . '%')
             ->get();

This will filter all the followers of User with id 1 and only get the followers that have the search query in their name or lastname

EDIT 2:

For the above to work you need relationships set up both ways:

User model:

function followers() {
    return $this->hasMany(Follower::class)
}

Follower model:

function user() {
    return $this->belongsTo(User::class)
}

This will enable you to get the followers for a specified user