首页 > 解决方案 > laravel中的传入和传出好友请求

问题描述

我想在我的 laravel 应用程序中创建友谊系统,所以我需要加载所有用户(传入请求、传出请求和其他新用户)为此我的控制器是这样的

$users = User::with([
            'friendships' => function ($query) {
                $query->where('sender_id', Auth::id());
            }
        ])
        ->where('users.id', '!=', Auth::id())
        ->get();

我的观点

@foreach($records as $i=>$all_user)
    <tr>
      <td>{{++$i}}</td>
      <td>{{$all_user['name']}}</td>
      <td>{{$all_user['email']}}</td>
      @forelse($all_user['friendships'] as $req_status)
        <td><a href="{{ url('/send_req') }}/{{$all_user->id}}" class="btn btn-success">{{$req_status->status}}</a></td>   
      @empty
        <td><a href="{{ url('/send_req') }}/{{$all_user->id}}" class="btn btn-primary">send Req</a></td>
      @endforelse   
    </tr>
    @endforeach

但是这段代码有很多缺陷。我得到了除登录用户之外的所有用户,但没有传入请求的记录。因此,如果用户有任何传入请求,那么我认为应该更改状态

我的用户模型是这样的

function friendships()
    {
        return $this->hasMany('App\Friendship','recipient_id','id');
    }

友谊表是

Schema::create(config('acquaintances.tables.friendships'), function (Blueprint $table) {
            $table->id();
            $table->morphs('sender');
            $table->morphs('recipient');
            $table->string('status')->default('pending')->comment('pending/accepted/denied/blocked/');
            $table->timestamps();
        });

标签: laravel

解决方案


有一个包可以帮助您轻松地在 laravel 中建立一个友谊系统,就像 个人没有使用它一样,我在我的一个投资组合项目中做了一个跟随系统,在这里有一个请求接受系统

我建议您手动尝试的是接近此的东西。

用户模型的友好特征

public function sentRequests()
{
    return $this->belongsToMany('App\User', 'friendships', 'user_id', 'friend_id');
}

public function recievedRequests()
{
    return $this->belongsToMany('App\User', 'friendships', 'friend_id', 'user_id');
}

public function friends()
{
    $sentAccepted = $this->sentRequests()->wherePivot('accepted', true)->get();
    $recievedAccepted = ->$this->friendOf()->wherePivot('accepted', true)->get();

    return $sentAccepted->merge($recievedAccepted); 

}

public sendRequest(User $user){
      $this->sendRequests()->create(['friend_id' , $user->id]);
}
public acceptRequest(User $user){
     $request_id = $this->recievedRequests()->where('friend_id' , $user->id)->first()->id;
     if($request_id) {
         return $this->recievedRequests()->updateExistingPivot($request_id , ['accepted' => true]) ;
     }
     return false ;
}
 

友谊表

Schema::create('friendships', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
    $table->foreignId('friend_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
    $table->timestamps();
    $table->boolean('accepted')->default(false);
    $table->timestamps();
});

推荐阅读